Using throw, catch and instanceof to handle Exceptions in Java
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:
Output in case of either of the exceptions:
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) 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:
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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.