Handle Multiple Exceptions in a catch Block
If you are catching a lot of exceptions in a single try block, you will notice that the catch block code looks very ugly and mostly consists of redundant code to log the error, keeping this in mind Java 7 one of the features was the multi-catch block where we can catch multiple exceptions in a single catch block.
Each exception type that can be handled by the catch block is separated using a vertical bar or pipe |.
Example 1:
Java
public class MutipleExceptionSingleCatch {public static void main(String[] args) {try {int array[] = new int[5];array[5] = 5 / 0;} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {System.out.println(e.getMessage());}}}
Output
/ by zero
Example 2:
Java
In the below code we are trying to catch the exception with the parent so it will give to compiler an exception
public class MutipleExceptionSingleCatch {public static void main(String[] args) {try {int array[] = new int[5];array[5] = 5 / 0;} catch (ArithmeticException | Exception e) {System.out.println(e.getMessage());}}}
In this example, ArithmeticException is a subclass of the Exception class. So, we get a compilation error.
Multiple catch blocks
Example 1: When matches any exceptions
Java
public class MutipleExceptionSingleCatch {public static void main(String[] args) {try {int array[] = new int[5];array[5] = 5 / 0;} catch (ArrayIndexOutOfBoundsException e) {System.out.println(e.getMessage());} catch (ArithmeticException e) {System.out.println(e.getMessage());}}}
Output
/ by zero
Example 2: When no exception matches then catch the base exception.
Java
import java.io.File;public class MutipleExceptionSingleCatch {public static void main(String[] args) {@SuppressWarnings("unused")File file = null;try {String pathname = null;file = new File(pathname);} catch (ArrayIndexOutOfBoundsException e) {System.out.println(e.getMessage());} catch (ArithmeticException e) {System.out.println(e.getMessage());} catch (Exception e) {System.out.println("Base Exception");}}}
Output
Base Exception
Exception Handling Using Throw keyword
Exception Handling Using Throws keyword
Java try/ catch block exception handling
Java catch Multiple Exceptions
Java nested try block exception handling
Java custom exception handling
No comments:
Post a Comment