Catch multiple exceptions is a Java 1.7 feature, we can handle multiple types of exceptions in a single catch block.
Let’s we check the difference before java 1.7 version and from java 1.7 version
Before Java 1.7 version
In Java 1.6 and early versions, if multiple exceptions occur in try block then we use separate catch block for every exception handling even though those exceptions have same handling code.
The drawbacks with multiple catch blocks:
=> It increases the program code and decreases the readability of the program.
=> We must write catch block for every exception handling.
=> It is complexity to the programmer.
In this program, in try block occurs different type of exceptions that we handled in separate catch block for every exception. Assume that first two catch blocks having same handling code but we handled in the separate catch blocks and also second two catch blocks.
package com.exceptions;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class MultiCatchTest {
public static void main(String[] args) {
try {
PrintWriter pw=new PrintWriter("abc.txt");
int i=10/0;
}
catch (FileNotFoundException e) {
System.out.println(e);
}
catch (ArithmeticException ae) {
System.out.println(ae);
}
catch (NullPointerException e) {
e.printStackTrace();
}
catch (ClassCastException e) {
e.printStackTrace();
}
}
}
From Java 1.7 version: catch multiple exceptions
From Java 1.7 version onwards we can write single catch block to handle multiple types of exceptions.
Every exception class is separated by vertical bar ( | ) in catch block
Advantages of catch multiple exceptions:
=> It decreases the program code and increases the readability of the program.
=> Easy to write for the developer.
package com.exceptions;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class MultiCatchTest {
public static void main(String[] args) {
try {
PrintWriter pw=new PrintWriter("abc.txt");
int i=10/0;
}
catch (FileNotFoundException | ArithmeticException e) {
System.out.println(e);
}
catch (NullPointerException | ClassCastException e) {
e.printStackTrace();
}
}
}
No choice to write parent and child exception or same exception classes in the same catch block.
catch (ArithmeticException | Exception e) {
System.out.println(e);
}
OR
catch (ArithmeticException | ArithmeticException e) {
System.out.println(e);
}
In this case, we will get compile time error as
The exception ArithmeticException is already caught by the alternative Exception
No comments:
Post a Comment