Multi Exception Handler



  • A new multi-catch clause, separated with vertical bars,has been introduced in Java7.
  • The new multi-catch clause reduces the amount of code by eliminating the need to write multiple catch clauses performing same action.
  • Catching Exception prevents you from noticing other types of exceptions.
  • The type alternatives that are separated with vertical bars cannot have an inheritance relationship.


try
{
some code here.....
}
catch(ExceptionType1 | ExceptionType2 | ExceptionType3 )
{
some code here
}



Example:MultiCatch

import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.Scanner; import java.sql.*; public class MultiCatchDemo { public static void main(String[] args) { System.out.println("Open a file"); try (InputStream in = new FileInputStream("myfile.txt"); Scanner s = new Scanner(in);) { System.out.println("File open"); int data = s.nextInt(); } catch (SQLException|IOException|ArithmeticException e) { System.out.println(e.getClass().getName()); System.out.println("ThankYou"); } } }