Subscribe
Tutorial search

Catch Multiple exceptions in Java - Java tutorial


Learn how to catch multiple exceptions in Java and handle them
Category: Java tutorials - Difficulty:




Using Multiple Catch Statements

A single try block can have many catch blocks. This is necessary when the try block has statements that raise different types of exceptions.

For e.g.

The following code traps three types of exceptions:

public class TryCatch

{

public static void main (String args[ ])

{

int array [] = {0,0};

int num1, num2, result = 0;

num1 = 100;

num2 = 0;

try

{

result = num1/num2;

System.out.println (num1/array [2]);

}

catch (ArithmeticException e)

{

System.out.println (“Error….Division by zero”);

}

catch (ArrayIndexOutOfBoundsException e)

{

System.out.println (“Error…. of Bounds”);

}

catch (Exception e)

{

System.out.println(“Error…”);

}

System.out.println (“The result is : “+result);

}

}

Handling the Unreachable Code Problem

The multiple catch blocks generate unreachable code error. If the first catch block contains the Exception class object then the subsequent catch blocks are never executed. The exception class being the super class of all the exception classes catches various types of exceptions.

The java complier gives an error stating that the subsequent catch blocks have not been reached. This is known as Unreachable code problem. To avoid this, the last catch block in multiple catch blocks must contain the Exception class object.