Java 7 Catch Multiple Exceptions

Java 7 Catch Multiple Exceptions

Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code.

You can use vertical bar (|) to separate multiple exceptions in catch block.

An old, prior to Java 7 approach to handle multiple exceptions.

Catching Multiple Exception Types Example 1

  1. public class MultipleExceptionExample{
  2.     public static void main(String args[]){
  3.         try{
  4.             int array[] = newint[10];
  5.             array[10] = 30/0;
  6.         }
  7.         catch(ArithmeticException e){
  8.             System.out.println(e.getMessage());
  9.         }
  10.         catch(ArrayIndexOutOfBoundsException e){
  11.             System.out.println(e.getMessage());
  12.         }
  13.         catch(Exception e){
  14.             System.out.println(e.getMessage());
  15.         }
  16.      }
  17. }

Output:

/ by zero

Catching Multiple Exception Types Example 2

What Java 7 provides us:

  1. public class MultipleExceptionExample{
  2.     public static void main(String args[]){
  3.         try{
  4.             int array[] = newint[10];
  5.             array[10] = 30/0;
  6.         }
  7.         catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
  8.             System.out.println(e.getMessage());
  9.         }
  10.      }
  11. }

Output:

/ by zero

Catching Multiple Exception Types Example 3

  1. public class MultipleExceptionExample{
  2.     public static void main(String args[]){
  3.         try{
  4.             int array[] = newint[10];
  5.             array[10] = 30/0;
  6.         }
  7.         catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException e){
  8.             System.out.println(e.getMessage());
  9.         }
  10.      }
  11. }

Output:

Compile-time error: The exception ArithmeticException is already caught by the alternative Exception

So here, in case when your are catching multiple exceptions, follow the rule of generalized to more specialized. It means that, if you are using super (general) class, don’t use child (specialized) class.

Note – Catch block which handles more than one exception type makes the catch parameter implicitly final. In the above example, the catch parameter “e” is final and therefore you cannot assign any value to it.

Next TopicJava Try with Resources

 

java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

Java 7 Catch Multiple Exceptions Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block. An old, prior to Java 7 approach to handle multiple exceptions. Catching Multiple […]

Tags:

....
...