Before learning about catching multiple exceptions, you need to be familiar with basic exception handling in Java. Moving forward, we assume you are familiar with a try and catch block in Java.
Why do we need multiple catch blocks in Java?
Multiple catch blocks in Java are used to handle different types of exceptions. Before Java 7 was launched, we needed a specific catch block to catch a specific exception. This created blocks of redundant code and hence resulted in an inefficient approach. Have a look at the following example to witness caught exceptions. It uses separate catch blocks for different kinds of exceptions.Example using Separate Catch Blocks
import java.util.Arrays;
public class ExceptionHandler {
public static void main(String[] args) {
Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1, 0 };
try {
System.out.println("Total number of options on a dice are: " + Arrays.toString(colorsOfASpectrum));
// un-comment the following line to see "Index Out of Bounds Exception"
// colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception
System.out.println(colorsOfASpectrum[0] / 0); // Arithmetic Exception
} catch (ArrayIndexOutOfBoundsException e) {
// This catch block executes in case of "Index Out of Bounds Exception"
System.out.println("Array Index Out Of Bounds Exception " + e);
} catch (ArithmeticException e) {
// This catch block executes in case of "Arithmetic Exception"
System.out.println("Arithmetic Exception " + e);
}
System.out.println("\n----Rest of the code executes here----");
}
}
Output
Total colors on a spectrum are: [7, 6, 5, 4, 3, 2, 1]
Exception Encountered java.lang.ArithmeticException: / by zero
----Rest of the code executes here----
As you can see, in the example above a different block is executed when an exception is thrown. There is a more efficient way to catch multiple exceptions using the same block of code for catching exceptions of different types. Have a look at the following example.
Example using Multiple Catch Block in Java
import java.util.Arrays;
public class MultiExceptionHandler {
public static void main(String[] args) {
Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1 };
try {
System.out.println("Total colors on a spectrum are: " + Arrays.toString(colorsOfASpectrum));
// colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception
System.out.println(colorsOfASpectrum[0] / 0); // Arithmetic Exception
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
// We don't need two different catch blocks for different kinds of exceptions
// Both exceptions will be handled using this multiple catch block
System.out.println("Exception Encountered " + e);
}
System.out.println("\n----Rest of the code executes here----");
}
}
Output
You can un-comment line 13 for printing out the exception of other kind.Total colors on a spectrum are: [7, 6, 5, 4, 3, 2, 1]
Exception Encountered java.lang.ArithmeticException: / by zero
----Rest of the code executes here----
GO TO FULL VERSION