try with multiple catch-block in Java

In this article, we will discuss try with multiple catch-block with examples and also see why it is required?

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

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:

Case 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

Case 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

 

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

Screen-capture for RuntimeException from Eclipse IDE:

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

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

 

References:

 

Read Also:

 

Happy Coding !!
Happy Learning !!

Nested try-catch block in Java Exception handling
Various methods to print exception information in Java