Multiple catch in Java

Java 8Object Oriented ProgrammingProgramming

To catch different exceptions generated by a single try block, we use the multiple catch block in Java.

The syntax for a multi-catch block is as follows −

try {
}
catch(Exception1 | Exception2 | Exception3…..| ExceptionN exception_obj)
{
}

Let us see a program for multiple catch block in Java −

Example

 Live Demo

import java.util.Scanner;
public class Example {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      try {
         int n = Integer.parseInt(sc.next());
         System.out.println(n/0);
      }
      catch (ArithmeticException | NumberFormatException e) {
         System.out.println("Exception Caught: " + e);
      }
   }
}

The output depends on the input.

For the following input −

5

Output

For the following input −

Exception Caught: java.lang.ArithmeticException: / by zero


Hello

Output

Exception Caught: java.lang.NumberFormatException: For input string: "Hello"
raja
Published on 08-Jan-2019 10:16:43
Advertisements