Multi catch Block in Java

A method can throw more than one exceptions. To handle these exceptions we need multiple catch blocks associated with the single try block.

 

A single try block can have multiple catch blocks. This is required when the try block has statements that generate different types of exceptions. If the first catch block contains the Exception class object then the subsequent catch blocks are never executed. The last catch block in multiple catch blocks must contain the Exception class object. This is because the Java compiler gives an error saying that the subsequent catch blocks haven’t been reached. This is known as Unreachable code problem.

 

Let’s understand this with an easy example.

The output of the above code will be – java.lang.ArrayIndexOutOfBoundsException: 4

Because in the above code we have two expected exceptions one at

arr[4] = 4; and another at  result = num1 / num2;

The first arr[4] = 4; will execute so we are getting Array out of Bound error. If you will comment out this line then you will get the ArithmeticException exception.

 

Selenium Testing Video Tutorial:

 

Let’s understand the working of multi-catch, Inside the try block when the exception is thrown then type of the exception thrown is compared with the type of exception of each catch block. If the type of exception thrown is matched with the type of exception from catch then it will execute corresponding catch block.

 

But there are some points to remember about catch block declaration –

  • At a time only single catch block can be executed. After the execution of catch, block control goes to the statement next to the try block.

  • At a time, an Only single exception can be handled.

  • All catch blocks must be ordered from most specific to most general.

0 Comment

Leave a Reply