InterviewSolution
| 1. |
Multi-catch block in Java |
|
Answer» Before Java 7 when we needed to handle more than one exception, we required multiple catch blocks to handle those exceptions. Let us see an example: import java.util.*; 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 ex) { System.out.println("Exception caught " + ex); } catch (NumberFormatException ex) { System.out.println("Exception caught " + ex); } } }The output here depends on the input. When we input an integer it will generate an arithmetic exception. For the following input: 3The output would be as follows: $javac Example.java $java ExampleException caught java.lang.ArithmeticException: / by zeroFor a String or character input, the output would be different. For the following input: HelloThe output would is as follows: $javac Example.java $java Example Exception caught java.lang.NumberFormatException: For input string: "Hello"From Java 7, the multi-catch block was INTRODUCED in Java A single catch block could catch multiple exceptions which are separated | symbol. Let us see an example for the multi-catch block: import java.util.*; 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 (NumberFormatException | ArithmeticException ex) { System.out.println("Exception caught " + ex); } } }When we input an integer it will generate an arithmetic exception. For the following input: 3The output would be as follows: $javac Example.java $java Example Exception caught java.lang.ArithmeticException: / by zeroFor a String or character input, the output would be different. For the following input: HelloThe output would is as follows: $javac Example.java $java Example Exception caught java.lang.NumberFormatException: For input string: "Hello" |
|