In this article, we will discuss try with multiple catch-block with examples and also see why it is required ?
1. try-catch block:
- Already, in the earlier article we have discussed about try-catch block for exception handling
- Here, exception raised from try-block will be caught in the catch-block and corresponding handler-code gets executed
2. Why multiple-catch blocks required ?
With try-block, there is also a possibility of throwing multiple exceptions from same program, like when we are dealing with
- Arithmetic calculation
- String operation
- Conversion of string to number
- Working with Array for accessing & assigning values
So, in these cases one catch-block to catch all types of exception is very much possible but it is not recommended
Reason:
- we might need to provide different handler-code for different exceptions
Solution:
- So, to achieve this we need to program with try with multiple catch-blocks
- In each catch-block provide different handler-code when catching different exception
Let us program for some cases:
2.1 One catch-block for every type of exception:
- Possible but NOT recommended
OneCatchBlockForAllTypesOfException.java
package in.bench.resources.exception.handling;
public class OneCatchBlockForAllTypesOfException {
public static void main(String[] args) {
try {
// code which might raise exception
// arithmetic operation
int result = 18/0;
System.out.println("Result of division : "
+ result);
// String operation
String str = null;
System.out.println("Lenght of the String : "
+ str.length());
// Number conversion
String s1 = "abc";
int convertedInt = Integer.parseInt(s1);
System.out.println("Converted integer : "
+ convertedInt);
// Array operation
char[] ch = new char[4];
ch[7] = 'B';
}
catch(Exception ex) {
// corresponding handling code,
// if any exception from try block
System.out.println(ex.toString());
}
finally {
// finally block always gets executed
// for code clean-up activities
System.out.println("finally block"
+ " always gets executed");
// rest of the code clean-up
}
}
}
Output:
java.lang.ArithmeticException: / by zero
finally block always gets executed
Explanation:
- In the above program for try-catch block, only one catch-block catches all types of exception
- Hence, handler provided remain same for every type of exception i.e.; printing name & description of the exception
- But in real-time scenario, the case may be different i.e.; providing different handling for different types of exception raised
- Assume that we are dealing with 2 types of resources i.e.; one is file handling and other is database interaction
- Exception for File resources: When program tries to access a remote file from one server location and if it’s not accessible and raises exception, then in this case alternate remote server location can be provided from handler-code
- Exception for Database resources: When program deals with database interaction, it is quite possible that sometime database is not available due to network issue; but in this case when exception is raised, alternate database location can be provided with correct credentials from handler-code
Let us move forward to code with multiple catch-blocks for different types of exception
2.2 try with multiple catch-block:
- Multiple catch-blocks for handling different types of exception
MultipleCatchBlockForDifferentTypesOfException.java
package in.bench.resources.exception.handling;
public class MultipleCatchBlockForDifferentTypesOfException {
public static void main(String[] args) {
try {
// code which might raise exception
// arithmetic operation
int result = 18/0;
System.out.println("Result of division : "
+ result);
// String operation
String str = null;
System.out.println("Lenght of the String : "
+ str.length());
// Number conversion
String s1 = "abc";
int convertedInt = Integer.parseInt(s1);
System.out.println("Converted integer : "
+ convertedInt);
// Array operation
char[] ch = new char[4];
ch[7] = 'B';
}
catch(ArithmeticException aex) {
// corresponding handling code,
// if any exception from try block
aex.printStackTrace();
}
catch(NullPointerException npex) {
// corresponding handling code,
// if any exception from try block
System.out.println(npex.toString());
}
catch(NumberFormatException nfex) {
// corresponding handling code,
// if any exception from try block
System.out.println(nfex.toString());
}
catch(ArrayIndexOutOfBoundsException aioobex) {
// corresponding handling code,
// if any exception from try block
System.out.println(aioobex.toString());
}
finally {
// finally block always gets executed
// for code clean-up activities
System.out.println("finally block always gets executed");
// rest of the code clean-up
}
}
}
Output:
java.lang.ArithmeticException: / by zero
finally block always gets executed
at in.bench.resources.exception.handling
.MultipleCatchBlockForDifferentTypesOfException
.main(MultipleCatchBlockForDifferentTypesOfException.java:12)
Explanation:
- In the above program, multiple catch-blocks are provided for catching different types of exception
- So, if any particular exception is raised then that corresponding catch-block will come into play by providing respective handler-code
- Here, we have simply printed the stack trace in the console for user information
- But in real-time scenarios, this comes very handy by providing different handler-code for different types of exception caught
3. Be cautious while declaring multiple catch blocks:
Few points to be noted for multiple catch-blocks,
- For try with multiple catch-block, order of exception declaration is very important
- That’s, most specific exception must come up 1st in the order followed by more general exception
- In other words, if there exists parent-child relationship between 2 exception then child exception must come 1st up in the order and then followed by parent exception
- Otherwise, compile-time error will be thrown stating “Exception Name-Of-Exception has already been caught”
- Also, declaring multiple catch-block with same type of exception results in compile-time error stating “Unreachable catch block for <Exception-Type>. It is already handled by the catch block for <Exception-Type>”
- Note: at any given point of time only one exception is thrown from try-block and only one catch-block is executed & rest of the catch-blocks remain un-executed
Let us consider one scenario to understand where compile-time error is thrown when declaring multiple catch blocks in wrong order
- Both RuntimeException and ArithmeticException are sub-type of Exception i.e.;
- ArithmeticException extends RuntimeException
- If Exception type comes at the top of the order while declaring multiple catch-blocks before RuntimeException or AithmeticException
- Then, compile-time error will be thrown stating “Unreachable catch block for RuntimeException. It is already handled by the catch block for Exception”
- Thus, it is very important to understand the relation between different types of exception
- Let us write one demo for this case with output and screen-capture from Eclipse IDE
- For exception hierarchy, read Exception Hierarchy in detail
MultipleCatchBlocksInWrongOrderOfException.java
package in.bench.resources.exception.handling;
import java.io.IOException;
public class MultipleCatchBlocksInWrongOrderOfException {
public static void main(String[] args) {
try {
// code which might raise exception
// arithmetic operation
int result = 18/0;
System.out.println("Result of division : "
+ result);
}
catch(Exception ex) {
// corresponding handling code,
// if any exception from try block
ex.printStackTrace();
}
catch(RuntimeException rtex) {
// corresponding handling code,
// if any exception from try block
System.out.println(rtex.toString());
}
catch(ArithmeticException aex) {
// corresponding handling code,
// if any exception from try block
System.out.println(aex.toString());
}
finally {
// finally block always gets executed
// for code clean-up activities
System.out.println("finally block"
+ " always gets executed");
// rest of the code clean-up
}
}
}
Output:
Compile-time error will be thrown at 2 places,
Place 1 Unreachable catch block for RuntimeException.
It is already handled by the catch block for Exception
Place 2 Unreachable catch block for ArithmeticException.
It is already handled by the catch block for RuntimeException
3.1 Screen-capture for RuntimeException from Eclipse IDE:
3.2 Screen-capture for ArithmeticException from Eclipse IDE:
Let us write one more demo program for multiple catch block with same type of Exception & screen capture from Eclipse IDE
3.3 Multiple catch block with same type of exception:
- Compile-time error: Unreachable catch block for ArithmeticException
- It is already handled by the catch block for ArithmeticException
Conclusion:
- So, it is highly recommended to provide multiple catch-blocks for each type of exception
- In Java 7, Sun people (now Oracle group) introduced new feature called multi-catch block
- where 2 or more exceptions can be grouped to provide same exception handler-code.
- Like this, we can have as many as multi-catch block
We will see this feature in the upcoming article which discusses about multi-catch block in detail with examples
Related Articles:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!