Handling Multiple Catch Clauses

Advertisement

So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.

Handling Multiple Catch Clauses

So far we have seen how to use a single
catch block, now we will see how to use more than one catch blocks in a single
try block.In java when we handle the exceptions then we can have
multiple catch blocks for a particular try block to handle many different kind
of exceptions that may be generated while running the program i.e. you can use
more than one catch clause in a single try block however every catch block can
handle only one type of exception. this mechanism is necessary when the try
block has statement that raise different type of exceptions.

When
an exception is thrown, normal execution is suspended. The runtime system
proceeds to find a matching catch
block that can handle the exception.
If no handler is found, then the exception is dealt with by the default
exception handler at the top level.

Lets
see an example given below which shows the implementation of multiple
catch blocks for a single try block.

In this example we have used two catch clause catching the exception
ArrayIndexOutOfBoundsException and ArithmeticException in which the statements
that may raise exception are kept under the try block. When the program is
executed, an exception will be raised. Now that time the first catch block
is skipped and the second catch block handles the error.

The multiple catch blocks can generate
unreachable code error i.e. if the first catch block contains the Exception
class object then the subsequent catch blocks are never executed. This is
known as Unreachable code problem. To avoid this, the last catch block in
multiple catch blocks must contain the genericclass object that is
called the Exception class. This exception class being the super class of
all the exception classes and is capable of catching any types of
exception. The generic Exception class can also be used with multiple catch
blocks.

In this example we didn't specify that which
one exception may occur during the execution of program but here we are trying
to access the value of an array that is out of bound still we don't need to worry about
handle the exception because we have used the Exception class that is responsible
to handle any type of exception.