Multiple Catch Blocks in Java

Introduction

The Try-Catch block in Java is used to handle exceptions. The code that might give an exception is written in the Try block and the Catch block handles the exception. The Try block comes first followed by the Catch block. You can also have a Finally block after the Catch block. In Java, you can use more than one Catch block to handle various types of exceptions. Each catch block must contain a different type of exception handler. If you feel that your program might give more than one type of exception, you can use multi-catch blocks.

Multi-Catch Block conventions

Multi-Catch blocks have two points that you must remember before using it:

  • At a time, only one exception is caught therefore only one catch block is executed or used.
  • The catch blocks should be arranged in a sequence such that the most specific catch block comes at the top and the most general block is the last block in the list. For example, the catch block for ArithmeticException should be placed before the catch block for Exception.

Example

public class DemoMultiCatch
{
public static void main (String [] args)
{

try
{
int a[] = new int [5];
a[5] = 30/0;
}
catch ( ArithmeticException e)
{
System.out.println ("Arithmetic Exception occurs");
}

catch ( ArrayIndexOutOfBoundsException e)
{
System.out.println ("ArrayIndexOutOfBounds Exception occurs");
}

catch ( Exception e)
{
System.out.println ("Parent Exception occurs");
}
System.out.println ("Hello World");
}
}

 

OUTPUT

Arithmetic Exception occurs
Hello World

In the above example, although we have three catch blocks, the exception that the try block sends to the catch block matches with the first type of exception that is the ArithmetixExpression. Therefore, only that block is executed and the execution continues outside of the try block. That is where we get the ‘Hello World’ string printed out.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.