dsa

Java Catch Multiple Exceptions

In this tutorial, we will learn to handle multiple exceptions in Java with the help of examples.

Catch Multiple Exceptions

Prior to Java 7, we had to catch only one exception type in each catch block. So whenever we needed to handle more than one specific exception, but take same action for all exceptions, then we had to have more than one catch block containing the same code.

Example :


// A Java program to demonstrate that we needed 
// multiple catch blocks for multiple exceptions 
// prior to Java 7 
import java.util.Scanner; 
public class Demo 
{ 
	public static void main(String args[]) 
	{ 
		Scanner sc = new Scanner(System.in); 
		try
		{ 
			int n = Integer.parseInt(sc.nextLine()); 
			if (11%n == 0) 
				System.out.println(n + " is a factor of 11"); 
		} 
		catch (ArithmeticException ex) 
		{ 
			System.out.println("Arithmetic " + ex); 
		} 
		catch (NumberFormatException ex) 
		{ 
			System.out.println("Number Format Exception " + ex); 
		} 
	} 
} 
Input 1

CodeMistic
Output
Number Format Exception java.lang.NumberFormatException: For input string: "CodeMistic"
Input 2

0
Output
Arithmetic Exception java.lang.ArithmeticException: / by zero

Catching Multiple Exceptions using pipe( | ) symbol

After Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in catch block.

For Example :

// A Java program to demonstrate multicatch feature
import java.util.Scanner; 
public class Test 
{ 
	public static void main(String args[]) 
	{ 
		Scanner sc = new Scanner(System.in); 
		try
		{ 
			int n = Integer.parseInt(sc.nextLine()); 
			if (11%n == 0) 
				System.out.println(n + " is a factor of 11"); 
		} 
		catch (NumberFormatException | ArithmeticException ex) 
		{ 
			System.out.println("Exception encountered " + ex); 
		} 
	} 
} 

Input 1

CodeMistic
Output
Exception encountered java.lang.NumberFormatException: For input string: "CodeMistic"
Input 2

0
Output
Exception encountered java.lang.ArithmeticException: / by zero
Note: