How do you handle different types of exceptions using multiple catch statements?

In Java, a single try block can have multiple catch blocks. When statements in a single try block generate multiple exceptions, we require multiple catch blocks to handle different types of exceptions. This mechanism is called multi-catch block in java.

Each catch block is capable of catching a different exception. That is each catch block must contain a different exception handler.

The syntax for using a single try with more than one catch block in java is as follows:

Syntax:

try 
{ 
  statements; 
} 
catch(ExceptionType1 e1) 
{ 
  statements; 
} 
catch(ExceptionType2 e2) 
{ 
  statements; 
} 
catch(ExceptionType3 e3) 
{ 
  statements; 
} 
  . . . 
catch(ExceptionTypen en) 
{ 
  statements; 
}

Java multi-catch block acts as a case in a switch statement. In the above syntax, if the exception object (ExceptionType1) is thrown by try block, the first catch block will catch the exception object thrown and the remaining catch block will be skipped.

In case, exception object thrown does not match with the first catch block, the second catch block will check, and so on.

At a time only one exception occurs and at a time only one catch block is used. All catch blocks must be arranged in such a way that exception must come from the first subclass and then superclass.


The diagrammatic representation of working of a single try block with multiple catch blocks is shown in the below figure.

How do you handle different types of exceptions using multiple catch statements?

For example, suppose we want to include catch blocks for Exception, RuntimeException, NullPointerException, and IOException with a single try block, they must be placed in the following order:

try 
{ 
  statements; 
} 
catch(NullPointerException np) 
{ 
  statements; 
} 
catch(RuntimeException re) 
{ 
  statements; 
} 
catch(IOException ieo) 
{ 
  statements; 
} 
catch(Exception e) 
{ 
  statements; 
}

Java Multiple Catch Blocks Example Program


Let’s take different kinds of example programs where a single try block will be followed by one or more catch blocks.

Program source code 1:

public class MultiCatchEx1 
{
public static void main(String[] args) 
{ 
try
{ 
 int arr[] = new int[6]; 
 arr[3] = 20/0; // Exception occurred. 
 System.out.println("I am in try block"); 
} 
catch(ArithmeticException ae)
{ 
 System.out.println("A number cannot be divided by zero, Illegal operation in java"); 
} 
catch(ArrayIndexOutOfBoundsException e)
{ 
 System.out.println("Accessing array element outside of specified limit"); 
} 
catch(Exception e)
{ 
 System.out.println(e.getMessage()); 
} 
System.out.println("I am out of try-catch block"); 
 } 
}
Output: 
       A number cannot be divided by zero, Illegal operation in java 
       I am out of try-catch block

Let’s take one more example program based on it.

Program source code 2:

public class MultiCatchEx2 
{
public static void main(String[] args) 
{ 
 String s = "Scientech Easy"; 
 int a[] = {0, 1, 2, 3, 4, 5};
try 
{ 
 s = null; 
 int sLength = s.length(); 
System.out.println("String length: " +sLength); 
int b = 6; 
System.out.println(a[b]); 
} 
catch(NullPointerException npe) 
{ 
 System.out.println("Exception is caught"); 
 System.out.println(npe.toString()); 
} 
catch(ArrayIndexOutOfBoundsException aie) 
{ 
 System.out.println("Exception is caught"); 
 System.out.println(aie.toString()); 
  } 
 } 
}
Output: 
      Exception is caught java.lang.NullPointerException

If you comment out line marked statement s = null; then you will get the following output.

Output: 
      String length: 14 
      Exception is caught java.lang.ArrayIndexOutOfBoundsException: 6

Program source code 3:

package exceptionHandling; 
import java.util.Scanner;
public class MultiCatchEx3 
{
public static void main(String[] args) 
{ 
 int x, y; 
 Scanner sc = new Scanner(System.in); 
try 
{ 
 System.out.println("Enter your first number"); 
 x = Integer.parseInt(sc.nextLine()); 
 System.out.println("Enter your second number"); 
 y = Integer.parseInt(sc.nextLine()); 

int z = x / y; 
System.out.println("z = " +z); 
} 
catch(ArithmeticException ae) 
{ 
 System.out.println("A number cannot be divided by 0, Illegal operation in Java"); 
 System.out.println("Exception thrown: " +ae); 
} 
catch(NumberFormatException nfe) 
{ 
 System.out.println("Invalid data types are entered, number must be an integer."); 
 System.out.println("Exception thrown: " +nfe); 
} 
catch(RuntimeException re) 
{ 
 System.out.println("Exception thrown: " +re); 
} 
System.out.println("Out of try-catch block"); 
 } 
}
Output: 
First Run: 
      Enter your first number 
      40 
      Enter your second number 
      20 
      z = 2 
      Out of try-catch block 
Second Run: 
      Enter your first number 
      40 
      Enter your second number 
      0 
      A number cannot be divided by 0, Illegal operation in Java Exception thrown: java.lang.ArithmeticException: / by zero 
      Out of try-catch block 
Third Run: 
      Enter your first number 
      40 
      Enter your second number 
      5.5 
      Invalid data types are entered, number must be an integer. 
      Exception thrown: java.lang.NumberFormatException: For input string: "5.5" 
      Out of try-catch block

Explanation:

In the above code, two different types of exceptions may be thrown within try block. First, ArithmeticException exception will be generated when division by zero operation is performed.

Second, NumberFormatException exception will be generated when we will enter a number of invalid data types like float, double, char, string, or even just press Enter.

In the first run of the program, no exception occurred because the division of two numbers has been simply performed.

In the second run of program, when the second number is input as zero, JVM checks that “division by zero” operation has been performed which is an illegal operation in java.

So, it will create an object of ArithmeticException class and throw it. This thrown object is caught by the first catch block that displays a user-defined message.

In the third run, the number of float type has been entered intentionally as input. In this case, Integer.parseInt cannot parse float number into integer.

So, JVM creates an exception of NumberFormatException class and throws it. This exception object is caught by the second catch block.

Note that in all program run, after handling exception by the catch blocks, statements after try-catch block has been executed.

What is Unreachable Catch Block Error?


When we are using multiple catch blocks for a single try block, the order of exceptions in the catch block must be placed in such a way that first, subclass exception comes and later on superclass exception.

If we place superclass exception first and later on subclass exception, all the exceptions thrown for subclass exception will be caught by the first catch block.

In this case, the second catch block will not be used in the program and java compiler will generate unreachable catch block error.

Let’s place superclass exception first and later on subclass exceptions in the catch block in the above program and see that java compiler shows unreachable catch block error or not.

Program source code 4:

package exceptionHandling; 
import java.util.Scanner;
public class MultiCatchEx4 
{
public static void main(String[] args) 
{ 
 int x, y; 
 Scanner sc = new Scanner(System.in); 
try 
{ 
 System.out.println("Enter your first number"); 
 x = Integer.parseInt(sc.nextLine()); 
 System.out.println("Enter your second number"); 
 y = Integer.parseInt(sc.nextLine()); 

int z = x / y; 
System.out.println("z = " +z); 
} 
catch(RuntimeException re) 
{ 
 System.out.println("Exception thrown: " +re); 
} 
catch(ArithmeticException ae) // Unreachable catch block error. 
{ 
 System.out.println("Exception thrown: " +ae); 
} 
catch(NumberFormatException nfe) // Unreachable catch block error. 
{ 
 System.out.println("Exception thrown: " +nfe); 
 } 
} 
}
try 
{ 
  statements; 
} 
catch(NullPointerException np) 
{ 
  statements; 
} 
catch(RuntimeException re) 
{ 
  statements; 
} 
catch(IOException ieo) 
{ 
  statements; 
} 
catch(Exception e) 
{ 
  statements; 
}
0

Hence, when using more than one catch block to catch different types of exceptions, it is very important to aware of the exception type and order in which they will be caught.

The order of exceptions must be arranged from more specific exception type to general exception type. Otherwise, a compile-time error occurs.


Hope that this chapter has covered all the important points related to multiple catch block in java with example programs. I hope that you will have understood and enjoyed this tutorial.

How multiple catch statements are used in exceptions?

Multiple Catch Block in Java Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.

How Multiple catch blocks can be used to handle the exceptions?

In Java, a single try block can have multiple catch blocks. When statements in a single try block generate multiple exceptions, we require multiple catch blocks to handle different types of exceptions. This mechanism is called multi-catch block in java. Each catch block is capable of catching a different exception.

What are the different ways to handle exceptions?

Here's a list of different approaches to handle exceptions in Java..
try...catch block..
finally block..
throw and throws keyword..

Can we catch multiple types of exceptions in a single catch block?

Handling More Than One Type of Exception The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar ( | ). Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final .