Open In App

Using throw, catch and instanceof to handle Exceptions in Java

Last Updated : 06 Feb, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite : Try-Catch Block in Java
In Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the ‘try’ block may be vulnerable to more than one exceptions. For example, take a look at the following sample code:




// A sample Java code with a try catch block
// where the try block has only one catch block
// to handle all possible exceptions
  
// importing class Random to generate a random number as input
import java.util.Random;
class A {
    void func(int n)
    {
        try {
  
            // this will throw ArithmeticException if n is 0
            int x = 10 / n;
            int y[] = new int[n];
  
            // this will throw ArrayIndexOutOfBoundsException
            // if the value of x surpasses
            // the highest index of this array
            y[x] = 10;
        }
        catch (Exception e) {
            System.out.println("Exception occurred");
        }
    }
    public static void main(String a[])
    {
        new A().func(new Random().nextInt(10));
    }
}


Output in case of either of the exceptions:

Exception occurred

As you can see from the above code, there is a possibility that either of the two exceptions mentioned above can occur. In order to handle them both, the catch statement is made to accept any exception that can occur by passing a reference to the Exception class, that is the parent of all exception classes. However, this catch statement does the same thing for all kinds of exceptions.

Specify Custom Actions for different Exceptions

In order to specify custom actions in such cases, programmers usually put multiple catch statements, such as in the following example:




// A sample Java code with one try block
// having multiple catch blocks to catch
// different exceptions
  
// importing class Random to generate a random number as input
import java.util.Random;
class A {
    void func(int n)
    {
        try {
  
            // this will throw ArithmeticException if n is 0
            int x = 10 / n;
            int y[] = new int[n];
  
            // this will throw ArrayIndexOutOfBoundsException
            // if the value of x surpasses
            // the highest index of this array
            y[x] = 10;
        }
        catch (ArithmeticException e) {
            System.out.println("Dividing by 0");
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("That index doesn't exist");
        }
    }
    public static void main(String a[])
    {
        new A().func(new Random().nextInt(10));
    }
}


Output:

a) In case of ArithmeticException: Dividing by 0
b) In case of ArrayIndexOutOfBoundsException: That index doesn't exist

Specify Custom Actions for different Exceptions using instanceof

However, there is a way to do the same thing by using only one catch block. To do so, java provides an operator: instanceof.
By using this operator, we can specify custom actions for the different exceptions that occur. The following program demonstrates how:




// Java program to demonstrate the use of
// instanceof to specify different actions for
// different exceptions using only one catch block
  
// importing class Random to generate a random number as input
import java.util.Random;
class A {
    void func(int n)
    {
        try {
  
            // this will throw ArithmeticException if n is 0
            int x = 10 / n;
            int y[] = new int[n];
            y[x] = 10;
  
            // this will throw ArrayIndexOutOfBoundsException
            // if the value of x surpasses
            // the highest index of this array
            System.out.println("No exception arose");
        }
        catch (Exception e) {
            if (e instanceof ArithmeticException)
                System.out.println("Can't divide by 0");
            if (e instanceof ArrayIndexOutOfBoundsException)
                System.out.println("This index doesn't exist in this array");
        }
    }
    public static void main(String a[])
    {
        new A().func(new Random().nextInt(10));
    }
}


Output:

a) In case of ArithmeticException: 
Can't divide by 0
b) In case of ArrayIndexOutOfBoundsException: 
This index doesn't exist in this array
c) In case of no exception: No exception arose

By using the instanceof operator in exception handling, it is easy to achieve the aforementioned objective and at the same time, it makes your code less complicated. One thing that has to be noted here is that as soon as the try block encounters an exception, the control will directly jump to the catch block, to handle, thereby, preventing the rest of the body of the try block from executing. As a result, even though there may be possibility of more than one exceptions occurring, the try block will only throw one exception, before shifting control to the catch block.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments