Using throw, catch and instanceof to handle Exceptions in Java
Last Updated :
06 Feb, 2019
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:
Java
// 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:
Java
// 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
// 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.
Similar Reads
How to Handle a java.lang.ArithmeticException in Java?
In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException. ArithmeticException can be defined as a runtime exception that ca
2 min read
Version Enhancements in Exception Handling introduced in Java SE 7
In this article, the enhancements made by Oracle in version 1.7, along with its implementation, has been discussed. As a part of 1.7 version enhancement, in Exception Handling, the following two concepts have been introduced by Oracle: Try with resources. Multiple catch blocks. Try with resources Un
4 min read
Java Program to Use finally block for Catching Exceptions
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occ
3 min read
Java Program to Handle the Exception Hierarchies
Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program and terminates the program. Exception Handling: The process of dealing with exceptions is known as Exception Handling. Hierarchy of Exceptions:
4 min read
Java Program to Handle Checked Exception
Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error. Â ClassNotFoundExcept
5 min read
Java Program to Handle Unchecked Exception
Exceptions are the issues arising at the runtime resulting in an abrupt flow of working of the program. Remember exceptions are never thrown at the compile-time rather always at runtime be it of any type. No exception is thrown at compile time. Throwable Is super-class of all exceptions and errors t
4 min read
Java Program to Handle Divide By Zero and Multiple Exceptions
Exceptions These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. Handling Multiple exceptions: There are two methods to handle multiple exceptions in java. Using a Single try-catch block try statement a
3 min read
How to Handle Timeouts in Network Communication in Java?
In Java, Timeouts in Network Communication mean when the end user sends a request to the server through a network, the server takes a lot of time to process the request and send it the in form of a response. In real-time applications we need to handle this situation for end users we need to give one
4 min read
Java Program to Handle Runtime Exceptions
RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation of the Java VM (Virtual Machine). The RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastE
2 min read
Java Program to Handle the Exception Methods
An unlikely event which disrupts the normal flow of the program is known as an Exception. Java Exception Handling is an object-oriented way to handle exceptions. When an error occurs during the execution of the program, an exception object is created which contains the information about the hierarch
4 min read