× back Packages Exceptions in Java Exception Handling Exception Hierarchy in Java Try & Catch blocks finally block "throw" keyword "throws" keyword Previous Year Questions
Next Topic → ← Previous Topic

Packages / Exception handling

Packages in Java

Packages in Java can be classified as:

Some commonly user predefined packages in Java include:

Inside java package

Note: When using the "import java.awt.*" statement, it will include only the classes from the specified package, not its subpackages. To include classes from a subpackage, you must import it explicitly. For example: to include classes from the "java.awt.event" subpackage, you should use the statement "import java.awt.event.

That's why java.* won't include everything because there are no classes directly inside the java package; instead, it contains subpackages. In Java, packages are used to organize and structure code. The java package serves as the root package for many core Java libraries, and it houses various subpackages, each responsible for specific functionalities or components.

  • For instance, you will find subpackages like java.util, java.io, java.awt, java.sql, and more within the java package. These subpackages, in turn, contain classes, interfaces, and other resources related to their respective domains. To access the classes within these subpackages, you must import them explicitly in your code using statements like import java.util.* or import java.awt.*, as the wildcard * includes all classes from the specified subpackage.

Term "import static"

Syntax ↓

                    
import static java.lang.System.*;
                    
                

Example ↓

                    
import static java.lang.System.*;

// Incorrect usage:
// import static java.util.*; // This is not allowed

class Test {
    public static void main(String[] args) {
        out.println("Hello World"); // No need to use the keyword 'System' every time
        out.println("How are you???");
    }
}
                    
                

Explanation:

  • The term "import static" in Java allows you to access static members (fields and methods) of a class directly without specifying the class name each time. In the example provided, we use import static for the 'java.lang.System' class. This means that we can directly access the static members of the 'System' class without having to prefix them with 'System.'.
  • However, it's important to note that import static doesn't work with wildcard imports like 'import static java.util.*;'. You can only use import static for specific classes and their static members.
  • In the example, when out.println(...) is used, we no longer need to use the keyword System because of the import static. This feature can improve code readability when dealing with frequently used static members.
  • In Java, when you want to import and use static members from a class using the import static feature, it's essential to specify the class name followed by a '.*' wildcard. This combination, 'import static some.package.SomeClass.*', allows you to import and make available all static members (fields and methods) of the specified class within your code. Omitting the '.*' part when using import static will result in the import statement not functioning as intended, and you won't be able to access the static members without referencing the class explicitly in your code.

Creating our own Package in Java

  • Creating a package in Java is a straightforward process, but effectively using it may require some understanding. Let's take a simple class and transform it into a package.
                    
class Shape {
    void color() {
        System.out.println("Coloring the shape");
    }
    void cal_area() {
        System.out.println("Calculating area.");
    }

    void cal_square() {
        System.out.println("Calculating square");
    }
}
                    
                
  • If we want to reuse the color(), cal_area(), and cal_square() methods without duplicating the code every time, we can achieve this using a package. To convert the file into a package, we make the following changes:
                    
// Shape.java file
package group;

public class Shape {
    public void color() {
        System.out.println("Coloring the shape");
    }
    public void cal_area() {
        System.out.println("Calculating area.");
    }
    public void cal_square() {
        System.out.println("Calculating square");
    }
}
                    
                
  • When creating a package, you can use any name following Java's naming conventions, typically using lowercase letters and adhering to a reverse domain naming scheme to avoid naming conflicts.
  • Classes and methods inside a package should generally be declared as either public or protected. The 'default' access modifier is limited to use within the same package, allowing classes to access each other without being explicitly declared as public or protected. Additionally, protected members (fields and methods) can be accessed by subclasses both within and outside the package, regardless of whether direct inheritance is involved.

Now that we have created our package file, let's use it:

  • Open your terminal and navigate to the folder where the package file is located.
  • Run the following command:
    
javac -d . filename.java
    
  • The above command will create a package folder instead of generating a .class file.
  • The dot (.) specifies that the package will be created in the current directory.
  • the -d option to specify the destination directory where the compiled .class files for the package should be placed.
  • Make sure that the package and the class in which are you going to import the package should be in same directory.
  • Now, you can use it as follows:
                    
// Test.java file where we will import our package and use the methods
import group.Shape.*;

class Test
{
    public static void main(String[] args)
    {
        // To avoid path errors, use the following
        group.Shape obj = new group.Shape();
        // Shape obj = new Shape(); // This might result in an error
        obj.color();
        obj.cal_area();
        obj.cal_square();
    }
}
                
            

Exceptions in Java

In Java, exceptions are events that occur during the execution of a program that disrupt the normal flow of instructions. Exceptions can occur for various reasons, such as division by zero, trying to access an array element that doesn't exist, or attempting to open a file that doesn't exist.
In Java, exceptions are a vital concept used to manage and handle runtime errors gracefully. They play a crucial role in achieving the goal of a robust programming language. Let's delve deeper into the world of exceptions:

Exception Handling

Exception handling is a fundamental aspect of Java programming that empowers developers to deal with runtime errors systematically. Java provides built-in support for exception handling, making it easier to write robust and reliable code. Here's a closer look at exception handling in Java:

                
int x = 10; 
int ans = x / 0; // Automatically handled by Java
String s1 = null; // also an exception
                
            

Exception Hierarchy in Java

In Java, exceptions are organized into a hierarchy of classes through inheritance. The java.lang.Throwable class serves as the root of this hierarchy.

Throwable (Root Class)

The Throwable class is the root class of the exception hierarchy in Java. It has two main subclasses:

Error

Error represents serious, unrecoverable system-level errors, often caused by the JVM or underlying hardware. Developers usually don't handle these exceptions, and they typically lead to program termination.

  • StackOverflowError: Occurs when the call stack (method call history) exceeds its limit.
  • OutOfMemoryError: Indicates that the JVM has exhausted available memory.

Exception

Exception represents exceptions that can be caught and handled by application code.
In Java, exceptions are classified into two main categories: checked exceptions and unchecked exceptions. These distinctions help developers handle and manage exceptions effectively in their code.

Checked Exceptions

  • Definition: Checked exceptions, also known as compile-time exceptions, are exceptions that the Java compiler mandates to be caught or declared in the code. This means that if a method can potentially throw a checked exception, it must be either caught using a try-catch block or declared using the 'throws' keyword in the method signature.
  • Examples: Common checked exceptions include 'IOException', 'FileNotFoundException', and 'SQLException'. These exceptions typically occur in situations where external resources or external systems are involved, and the developer needs to handle potential issues gracefully.
  • Handling: Developers are required to handle checked exceptions explicitly in their code, either by using try-catch blocks to catch and process the exception or by declaring the exception using 'throws' in the method signature.

Unchecked Exceptions

  • Definition: Unchecked exceptions, also known as runtime exceptions, are exceptions that do not require explicit handling using try-catch blocks or 'throws' declarations. These exceptions can be caught and handled, but it's not mandatory by the compiler.
  • Examples: Common unchecked exceptions include 'NullPointerException', 'ArrayIndexOutOfBoundsException', and 'ArithmeticException'. These exceptions usually result from programming errors or invalid operations and are not related to external factors.
  • Handling: While unchecked exceptions can be caught and handled if desired, developers are not required to do so. It is often recommended to address the root cause of these exceptions during development and not rely solely on catching them in code.

Understanding the difference between checked and unchecked exceptions is crucial for effective exception handling in Java. Checked exceptions help ensure that developers handle potential issues that may arise when interacting with external resources, while unchecked exceptions primarily address programming errors and invalid operations.

The Throwable class, along with its subclasses Error and Exception, forms the foundation of Java's exception handling system. Developers can create their custom exceptions by extending the Exception class or one of its subclasses.

When handling exceptions in Java, it's essential to catch specific exceptions based on the situation, which allows for more precise error handling and recovery.

Try & Catch Blocks in Exception Handling

Exception handling in Java involves several essential keywords, including try, catch, finally, throw, and throws. Let's dive into the details of how these keywords play a crucial role in managing exceptions:

Handling Exceptions by the User Using Try and Catch Blocks

Example ↓

                    
import java.util.Scanner;

class Exp {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int v1, v2, ans;
        System.out.println("Enter two numbers: ");
        v1 = sc.nextInt();
        v2 = sc.nextInt();

        ans = v1 / v2;
        System.out.println(ans);
    }
}
                    
                
  • In the above code, when we provide v2 = 0, we will get a 'DivideByZero' error, which is correctly handled by Java.
  • As we can see, the program is correct, but when v2 = 0, the code after that won't get executed because Java doesn't handle it, and that's why it gets terminated.
  • Now, if we want to handle it by the user, we will use the try-catch block.
    • Try block: Used for handling exceptions by the user. In the try block, we put the code that might generate an exception. If an exception is generated by the try block, it switches to the catch block, which is the exception handler.
  • If we are not sure which part will give an exception, then put the whole code inside the try block. Only the content that might generate an exception will be part of the try block, not any method.
                    
import java.util.Scanner;

class Exp {
    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);
            int v1, v2, ans;
            System.out.println("Enter two numbers: ");
            v1 = sc.nextInt();
            v2 = sc.nextInt();
            ans = v1 / v2;
            System.out.println(ans);
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}
                
            
  • Remember, try without catch won't work.
  • If we want to find which line caused the error and get its name, we can do the following:
                    
catch (Exception e) {
    System.out.println("Error occurred at line: " + e.getStackTrace()[0].getLineNumber());
    System.out.println("Error message: " + e.getMessage());
}
// This provides full details about the error.
                
            

Try with Multiple Catch Blocks

                    
import java.util.Scanner;

class Exp {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int v1, v2, ans;
        System.out.println("Enter two numbers: ");
        v1 = sc.nextInt();
        v2 = sc.nextInt();
        try {
            ans = v1 / v2;
            System.out.println(ans);
        }
        catch (InputMismatchException e1) {
            System.out.println("Exception due to wrong input datatype");
        }
        catch (ArithmeticException e2) {
            System.out.println("Exception due to dividing by zero");
        }
        catch (Exception e) { // Default, if we don't exactly know what can be the exception.
            System.out.println("Error: " + e);
        }
    }
}
                    
                
  • We can even put a try block inside another try block.

Multiple Try with Multiple Catch

Exception handling in Java is a critical aspect of ensuring that your programs can gracefully handle unexpected situations. Java provides several mechanisms for handling exceptions, including:

  • Automatic handling by the Java Virtual Machine (JVM)
  • Using the try/catch block
  • Using try with multiple catch blocks

When dealing with exceptions, try and catch blocks serve two main objectives:

  1. Provide user-defined error messages for better diagnostics.
  2. Allow the continuation of code execution even in the presence of exceptions. This ensures that other parts of the code can still run.

There is no strict limitation on the number of try and catch blocks you can use in your code. However, it's essential to consider code complexity as it may increase with a higher number of exception-handling blocks.

Continuation of Program:

  • Continuation of program flow is achieved using multiple try and catch blocks.
  • This approach is particularly useful when you know the class names of the exceptions you expect to handle.
  • Deciding how many try and catch blocks to use can be based on grouping the code into logical sections. Here are three common groups:
    • Input processing
    • Calculation
    • Display

    Both the input and calculation sections have a higher chance of encountering exceptions, so it's beneficial to place separate try and catch blocks for each group.

Example:

        
import java.util.*;

class ExceptionHandlingExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int v1 = 0, v2 = 0, ans = 0, sub = 0;
        System.out.println("Enter two numbers: ");
        try { // input
            v1 = sc.nextInt();
            v2 = sc.nextInt();
        } catch (InputMismatchException e1) {
            System.out.println("Error due to wrong input");
        }

        try { // calculation
            ans = v1 / v2;
            System.out.println("Division Result: " + ans);
        } catch (ArithmeticException e2) {
            System.out.println("Error due to division by zero");
        }

        try { // independent calculation
            sub = v1 - v2;
            System.out.println("Subtraction Result: " + sub);
        } catch (ArithmeticException e3) {
            System.out.println("Error due to subtraction");
        }
    }
}
        
    
  • It's a good practice to declare all variables before the first try block to ensure they have a broader scope.
  • If you don't know the specific exception class name, you can use the generic Exception class to catch and handle exceptions.

Nested Try-Catch Blocks in Java

In Java, when dealing with complex situations that involve multiple layers of exception handling, nested `try` and `catch` blocks can be employed. These blocks allow for a finer level of detail in handling exceptions at different levels of your code.

Understanding Nested Try-Catch Blocks:

Nested `try` and `catch` blocks involve placing one or more `try` blocks inside another. This approach is useful when certain operations within a `try` block can themselves trigger exceptions that need to be handled separately.

Example:

                    
try {
    // Outer try block
    // Perform some operations
    try {
        // Inner try block
        // Perform more specific operations
    } catch (SpecificException e) {
        // Handle the specific exception from the inner block
    }
    // Continue with operations
} catch (GeneralException e) {
    // Handle a more general exception from the outer block
}
                    
                

In the example above, the outer `try` block handles more general exceptions, while the inner `try` block handles exceptions specific to its operations. This way, you can provide specialized error-handling for different parts of your code.

Nesting for Specificity:

The key benefit of nested `try` and `catch` blocks is the ability to address specific exceptions without affecting the entire code block. It allows you to provide more specific error-handling strategies at different levels of your code.

Caution:

While nesting can be powerful for precise error handling, it can also make your code more complex. It's essential to strike a balance between specificity and code readability. Avoid excessive nesting, which can lead to code that's challenging to maintain.

Best Practices:

  • Use nested `try` and `catch` blocks when there's a genuine need to handle exceptions at different levels with varying levels of detail.
  • Keep your code organized and maintainable by providing clear comments and documentation.
  • Avoid deeply nested blocks when possible; instead, break down your code into smaller, more manageable functions or methods.
                            
import java.util.Scanner;

public class NestedTryCatchExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int v1, v2, ans, sub; 

        try {
            System.out.println("Enter two numbers: ");
            v1 = sc.nextInt();
            v2 = sc.nextInt();

            try {
                ans = v1 / v2;
                System.out.println("Division Result: " + ans);
            } catch (ArithmeticException e2) {
                System.out.println("Error: Division by zero is not allowed.");
            }

            try {
                sub = v1 - v2;
                System.out.println("Subtraction Result: " + sub);
            } catch (ArithmeticException e3) {
                System.out.println("Error: Subtraction operation resulted in an error.");
            }
        } catch (java.util.InputMismatchException e1) {
            System.out.println("Error: Invalid input. Please enter valid numbers.");
        }
    }
}
                            
                        

finally Block

Syntax:

                
try {
    // Code that may throw exceptions
}
catch (Exception e) {
    // Exception handling code
}
finally {
    // Code that always executes, whether or not an exception was thrown
}
                
            

Understanding the "throw" Keyword in Java

Handling the 'Divide by Zero' Exception Using the "throw" Keyword without Try-Catch Blocks

                    
import java.util.*;

class Test
{
    public static void main(String[] args)
    {
        int ans = 0;
        int v1 = 10;
        int v2 = 0;
        if(v2 == 0)
        {
            throw new ArithmeticException("Division by zero is not allowed.");
            // Alternatively, you can create an ArithmeticException object and then throw it:
            // ArithmeticException obj = new ArithmeticException("Division by zero is not allowed.");
            // throw obj;
        }
        else 
        {
            ans = v1 / v2;
        }
        System.out.println(ans);
    }
}
                
            

In the example above, we used the concept of anonymous objects.

  • Note: "throw" keyword is not used for predefined exception although the program will work but we should not use it, it should only we used for custom exceptions or user defined exceptions.
                    
class A
{
    public void sum(int v1)
    {
        System.out.println(v1 + 10);
    }
}
public static void main(String[] args) 
{
    (new A()).sum(5);
    // This is similar to the following:
    // A obj = new A();
    // obj.sum(5);
}
                
            

Throwing Unchecked Exceptions

  • We know that exceptions are of two types:
    1. Checked
    2. Unchecked
    Now, which one to create?? Although "throw" can handle both unchecked and checked exception but is better to use it for unchecked.
  • If we want to throw a checked exception, then we know that we extend the Exception class.
  • Now, for unchecked exceptions, we extend the RuntimeException class.

Steps to Create and Throw Our Custom Exception

  1. Inherit from the "RuntimeException" or "Exception" class to create our custom exception class.
  2. Create a constructor for the custom exception class.
                    
// Step 1: Inheriting from RuntimeException class to create our custom exception class
class YoungerAgeException extends RuntimeException {
    // Step 2: Creating a constructor that takes a custom error message
    YoungerAgeException(String msg) {
        super(msg);
    }
}

class Test {
    public static void main(String[] args) {
        int age = 16;
        if (age < 18) {
            throw new YoungerAgeException("You are not eligible to vote");
        } else {
            System.out.println("Please vote");
        }
        System.out.println("Hello"); // This message won't print if the exception is generated, which means the program will terminate abnormally.
    }
}
                    
                
  • Remember: Still, the program will terminate abnormally if age < 18. So, if we want to successfully execute our program, then we must use try and catch block.
  • So using "throw," we are creating an exception object, but the handling will be done by the try and catch block.
  • To correct it, we must use a try and catch block.
                    
class YoungerAgeException extends RuntimeException {
    YoungerAgeException(String msg) {
        super(msg);
    }
}

class Test {
    public static void main(String[] args) {
        int age = 16;
        try {
            if (age < 18) {
                throw new YoungerAgeException("You are not eligible to vote");
            } else {
                System.out.println("Please vote");
            }
        } catch (YoungerAgeException e) {
            System.out.println(e);
        }
        System.out.println("Hello"); // Now this will run
    }
}
                
            

Another Example: If a number is even, throw a custom exception.

                
class MyException extends Exception { // We could also extend RuntimeException here
    MyException(String str) {
        super(str);
    }
}

class Test {
    public static void main(String[] args) {
        int n1 = 10;
        try {
            if (n1 % 2 == 0) {
                throw new MyException("Number is even.");
            } else {
                System.out.println("Nothing is wrong");
            }
        } catch (MyException e) {
            System.out.println(e);
        }
    }
}
                
            
  • Remember: we can't write any statement after throw, otherwise it will provide unreachable statement error.

Understanding the 'super' Keyword in Java

Definition of the 'super' Keyword:

In Java, the 'super' keyword is a special word used to refer to the superclass or the parent class of the current class. It helps you access members (like variables or methods) from the superclass, especially when there are similarly named members in both the superclass and the subclass. The 'super' keyword is primarily used to handle conflicts and interact with superclass members in an inheritance hierarchy.

Simple Example for Beginners:

Let's illustrate the 'super' keyword with a straightforward example involving two classes: a superclass called Animal and a subclass called Dog. We'll show how 'super' can be used to access the constructor and method of the superclass.

                
<!-- Superclass -->
class Animal {
    String name;

    Animal(String name) {
        this.name = name;
    }

    void sound() {
        System.out.println("Animal makes a sound");
    }
}

<!-- Subclass -->
class Dog extends Animal {
    String breed;

    Dog(String name, String breed) {
        <!-- Using 'super' to call the superclass constructor -->
        super(name);
        this.breed = breed;
    }

    void sound() {
        <!-- Using 'super' to call the superclass method -->
        super.sound();
        System.out.println("Dog barks");
    }
}

<!-- Main Program -->
public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog("Buddy", "Labrador");
        System.out.println("Name: " + myDog.name);
        System.out.println("Breed: " + myDog.breed);
        myDog.sound();
    }
}
            
        

In this example, 'super' is used within the Dog constructor to call the constructor of the Animal superclass, passing the name parameter. It's also used within the sound method of the Dog class to call the sound method of the Animal class before adding specific behavior for the Dog class.

When you run this program, it demonstrates how 'super' allows you to use and extend functionality from the superclass when creating subclasses, promoting code reusability and organization in object-oriented programming.

throws keyword

Syntax:

    
public void myMethod() throws ExceptionType1, ExceptionType2 
{
    // Method body
}
    
                
public void myMethod() throws Exception // Parent class; mentioning this may consume more memory.
{
    // Method implementation
}
                
            

Understanding Thread.sleep and Exception Handling in Java (Next topic)

The Thread.sleep method is used to intentionally introduce a pause or delay in the execution of a Java program. When this method is called, the program suspends its execution for the specified duration in milliseconds. Importantly, during this pause, the program does not perform any tasks and does not continue from where it left off immediately. This behavior necessitates proper exception handling because Thread.sleep can throw an InterruptedException when interrupted during the sleep period. Exception handling is essential to ensure the program's stability and graceful response to interruptions.

                
class Test {
    public static void main(String[] args) {
        System.out.println("Welcome to the use of Throws statement");
        int n = 10;
        System.out.println(n);
        Thread.sleep(5000); // this will throw InterruptedException
        int j = 20;
        System.out.println(j);
    }
}
                
            
                
class Test {
    public static void main(String[] args) {
        System.out.println("Welcome to the use of Throws statement");
        int n = 10;
        System.out.println(n);
        try {
            Thread.sleep(5000); // this will throw InterruptedException
        } catch (InterruptedException e) {
            System.out.println(e);
        }
        int j = 20;
        System.out.println(j);
    }
}
                
            
                
class Test {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Welcome to the use of Throws statement");
        int n = 10;
        System.out.println(n);
        Thread.sleep(5000); // this will throw InterruptedException
        int j = 20;
        System.out.println(j);
    }
}
                
            

In summary, using the throws keyword in the method signature can make your code cleaner and more concise when dealing with Thread.sleep. It simplifies exception handling and is especially beneficial when you have multiple Thread.sleep calls in your code.

                        
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

class Test {
    // This method declares that it may throw a custom exception.
    public void divide(int numerator, int denominator) throws MyException {
        if (denominator == 0) {
            // Simulate a custom exception (for demonstration purposes).
            throw new MyException("Division by zero is not allowed.");
        }
        int result = numerator / denominator;
        System.out.println("Result: " + result);
    }

    public static void main(String[] args) {
        Test myObj = new Test();
        try {
            myObj.divide(10, 0);
        } catch (MyException e) {
            System.out.println("Caught an exception: " + e.getMessage());
        }
    }
}
                        
                    

throw vs. throws

    • throw: The 'throw' keyword is used to explicitly throw an exception object within a method. This means that when a specific exceptional condition is encountered within the method, you can use 'throw' to create and throw an exception object, indicating that something has gone wrong.
      Example:
                                          
      void m1() {
          throw new ArithmeticException();
      }
                                          
                                      
      In this example, we throw an 'ArithmeticException' explicitly, signaling that an arithmetic error has occurred.
    • throws: The 'throws' keyword, on the other hand, is used in a method's signature to declare that the method may potentially throw one or more specific exceptions. This declaration allows the method to pass the responsibility of handling these exceptions to its caller. When a method is declared with 'throws,' it means that the method is warning the caller that it might encounter certain exceptions during execution, and the caller needs to handle them.
      Example:
                                          
      void m1() throws ArithmeticException {
          // Method code
      }
                                          
                                      
      Here, 'throws' indicates that this method may throw an 'ArithmeticException,' and it's the caller's responsibility to handle it if necessary.
    • throw: The 'throw' keyword is always used inside the method body to explicitly throw an exception. It is typically used when an exceptional condition is detected within the method, and you want to trigger an exception immediately.
    • throws: In contrast, the 'throws' keyword is always used in the method's signature to declare exceptions that the method might propagate to the caller. It doesn't create or throw exception instances within the method but rather specifies the potential exceptions the method can raise.
    • throw: With 'throw,' you can throw only one exception at a time. Each 'throw' statement is responsible for throwing a specific exception.
      Example:
                                          
      throw new ArithmeticException();
                                          
                                      
      This line throws an 'ArithmeticException.'
    • throws: With 'throws,' you can declare and handle multiple exceptions simultaneously. This is especially useful when a method can potentially encounter different types of exceptions.
      Example:
                                          
      void m1() throws ArithmeticException, ArrayIndexOutOfBoundsException {
          // Method code
      }
                                          
                                      
      Here, the 'throws' keyword declares that 'm1' may throw either an 'ArithmeticException' or an 'ArrayIndexOutOfBoundsException.'
    • throw: The 'throw' keyword is followed by an instance of an exception class, indicating that you are creating and throwing a specific exception object. This allows you to customize the exception with details about the error.
    • throws: In contrast, the 'throws' keyword is followed by the names of exception classes. It doesn't create or throw exception instances directly but rather informs the caller of the potential exceptions that may be thrown by the method. The caller is then responsible for handling these exceptions as needed.

Programs

                        
import java.util.InputMismatchException;
import java.util.Scanner;

class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num1 = 0;
        int num2 = 0;
        
        try {
            System.out.println("Enter first number: ");
            num1 = sc.nextInt();
            
            System.out.println("Enter second number: ");
            num2 = sc.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("InputMismatchException: " + e.getMessage());
            // Clear the invalid input
            sc.next();
        }

        try {
            String str = "123Human";
            int num3 = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException: " + e.getMessage());
        }

        // Rest of your code
        int sum = num1 + num2;
        System.out.println("Sum: " + sum);
    }
}

                        
                    

Previous Year Questions

Illustrate the usage of throw and throws by using suitable example.

Define Exceptions in Java. Write a Java code to show the imiplementation of ArrayIndexOutOfBoundsExceptions and ArithmeticException.

State the difference between import and static import. Explain by using an example.

Define Arrays in Java and its classification. Write a programme to show the Exception ArrayIndexOutOfBoundsException.

Define Exception Explain the use of try and multiple catch in Java. Illustrate the difference between throw and throws in Java.

Define Packages. Name any five inbuilt packages in Java. Design a package called Shape and it contains Rectangle, square and Circle class. Write a programme to illustrate this.

Describe packages in Java. State the benefits of using packages in Java. Write a program to create package shape and add the following (as given below) in the package.

                
+---------------------+
|  Interface: Test    |
|---------------------|
|  Area(int l, int b) |
+---------------------+ 

+---------------------+
|  Class: Rectangle   |
|---------------------|
|  Area(int l, int b) |
+---------------------+ 
                
            

The above package must contain interface Test and Class Rectangle.

Reference