Java Multiple Catch Block
One or more catch blocks may come after a try block. Every catch block must have its exception handler. So, if you need to perform multiple tasks in response to different exceptions, use the Java multi-catch block.
Things to keep in mind
Only one exception occurs at a time, and only one catch block is performed. All catch blocks must be ordered from the most specific to the most general. For example, catch for ArithmeticException comes before catch for Exception.
Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}
Example:
public class FirstCode{
public static void main(String[] args) {
try{
int a[]=new int[2];
a[2]=15/0;
}
catch(ArithmeticException e)
{
System.out.println("Error: Arithmetic Exception");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: ArrayIndexOutOfBounds Exception");
}
catch(Exception e)
{
System.out.println("other Exception");
}
System.out.println("Welcome to FirstCode");
}
}
Output:
Error: Arithmetic Exception
Welcome to FirstCode
Notes
1. We should capture the base exception type if all exceptions are members of the same class hierarchy. However, each exception must be handled independently in its own catch block.
2. A single catch block can handle multiple types of exceptions. On the other hand, the base (or ancestor) class and subclass (or descendant) exceptions cannot be caught in a single line.
As an example, Exception is an ancestor of NumberFormatException, so catch(NumberFormatException | Exception ex) is not valid.
3. Vertical bar pipe | must be used to separate all exceptions.
Example:
Class FirstCode {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
In Java, a single try block can contain multiple catch blocks. When a single try block generates multiple exceptions, we need multiple catch blocks to handle them. This mechanism is known as a multi-catch block in Java.
Example:
public class CombinedMultipleCatchBlocks {
public static void main(String[] args) {
try {
// First Example
int a[] = new int[3];
System.out.println(a[5]);
} catch(ArithmeticException e) {
System.out.println("Error: Arithmetic Exception");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error: ArrayIndexOutOfBounds Exception");
} catch(Exception e) {
System.out.println("Error: Parent Exception");
}
try {
// Second Example
int a[] = new int[5];
a[5] = 30 / 0;
System.out.println(a[10]);
} catch(ArithmeticException e) {
System.out.println("Error: Arithmetic Exception");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error: ArrayIndexOutOfBounds Exception");
} catch(Exception e) {
System.out.println("Error: Parent Exception");
}
try {
// Third Example
String s = null;
System.out.println(s.length());
} catch(ArithmeticException e) {
System.out.println("Error: Arithmetic Exception");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error: ArrayIndexOutOfBounds Exception");
} catch(Exception e) {
System.out.println("Error: Parent Exception");
}
System.out.println("Welcome to FirstCode java tutorials");
}
}
Output:
Error: ArrayIndexOutOfBounds Exception
Error: Arithmetic Exception
Error: Parent Exception
Welcome to FirstCode java tutorials
Explanation
This code shows how to handle different exceptions in various scenarios using multiple try-catch blocks.
There are three distinct try-catch blocks in the primary method, each corresponding to an example given.
There is a specific example code that may throw various kinds of exceptions in each try block.
Catch blocks catch and handle certain types of exceptions, arranged from most specialised to most general.
Any unhandled exceptions are caught in the Exception catch block at the end.
The code’s message indicates the type of exception in each case.
Outside of the try-catch blocks, there is a statement that outputs “rest of the code.”
Advantages
- Precise Exception Handling: You can catch and handle specific exceptions using numerous catch blocks. Because you can personalise your answer to the sort of exception that occurred, you can handle errors more precisely.
- Maintainability: Using multiple catch blocks improves your code’s maintainability. When each exception type is handled in its own block, error-handling logic is easier to understand and adjust.
Disadvantages
Code Duplication: Code duplication might occur when many catch blocks contain similar or identical error-handling logic. If you need to adjust the error-handling logic for a specific exception type, it can make your code harder to manage and increase the risk of inconsistencies.
The arrangement of catch blocks is essential. If catch blocks for subclasses are placed before catch blocks for their superclass, the code for subclasses will never be reached. If not handled correctly, this can result in unexpected behaviour.
Conclusion
Using a single catch block to catch multiple exceptions reduces code duplication and increases efficiency. Because there is no code redundancy, the bytecode generated by this program’s compiler will be smaller than that generated by a compiler for a program with multiple catch blocks.