Background
Prior to Java 7, we only needed to catch one type of exception in each catch block. So if we have to handle more than one particular exception, but have to take action on all of them, we must have more than one catch block containing the same code.
In the following code, we need to handle two different exceptions, but take the same action on both. So we should have two different catch blocks from Java 6.0.
// A Java program to demonstrate that we needed // multiple catch blocks for multiple exceptions // prior to Java 7 import java.util.Scanner; public class Test { public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); } catch (ArithmeticException ex) { System.out.println("Arithmetic " + ex); } catch (NumberFormatException ex) { System.out.println("Number Format Exception " + ex); } } }
Input 1:
GeeksforGeeks
Output 1:
Exception encountered java.lang.NumberFormatException: For input string: "GeeksforGeeks"
Multicatch
As of Java 7.0, it is possible for a single catch block to catch multiple exceptions, each marked with | . separated (pipe symbol) in the catch block.
// A Java program to demonstrate multicatch // feature import java.util.Scanner; public class Test { public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); } catch (NumberFormatException | ArithmeticException ex) { System.out.println("Exception encountered " + ex); } } }
Input 1:
GeeksforGeeks
Output 1:
Exception encountered java.lang.NumberFormatException: For input string: "GeeksforGeeks"
Input 2:
0
Output 2:
Exception encountered java.lang.ArithmeticException: / by zero
A catch block that handles multiple types of exceptions does not duplicate in the bytecode generated by the compiler, i.e. the bytecode does not replicate any exception handlers.
Important Points:
// Not Valid as Exception is an ancestor of // NumberFormatException catch(NumberFormatException | Exception ex)