Java – Multi-Catch feature
With the help of multi-catch feature single catch clause can handle more than one exception.
It helps to reduce the code.
In multi-catch, exception types present in the catch clause are separated with the OR operator (|).
Example
import java.util.Scanner; class MultiCatchDemo { public static void main(String args[]) { System.out.println("Enter any number :: "); Scanner in = new Scanner(System.in); int num = in.nextInt(); in.close(); try { int i = 10/num; System.out.println(i); String str = null; System.out.println(str.length()); } catch(ArithmeticException | NullPointerException e) { System.out.println("Exception Handled"); } } }
Both ArithmeticException, as well as NullPointerException, are caught by single catch clause.
If we entered zero
Output
Enter any number :: 0 Exception Handled
If we entered any number other than zero
Output
Enter any number :: 2 5 Exception Handled
Note
Every parameter of multi-catch is final; therefore it can’t be reassigned.
Leave a reply