Multiple catch blocks and nested try blocks

Multiple catch blocks with single try block

Sometimes a set of statements combined can result in different types of exceptions. For example, when processing two arrays and performing division operation on each of the elements of an array, there is a possibility to get ArrayIndexOutOfBoundsException or ArithmeticException. In such cases how to handle them? This can be achieved by multiple catch blocks to a single try block. Below program explains the same functionality of Java. Here, denom array is having zeros and we are performing a division operation. Hence, I wrote two catch blocks which handle different types of exceptions.

/*
This is a simple Java program about Exception Handling.
Call this file KH_MaultipleCatch1.java.
*/

class KH_MaultipleCatch1 {
	public static void main(String args[]) {
		int number[] = { 4, 8, 16, 32, 64, 128, 256, 512 };
		int denom[]  = { 2, 0, 4, 4, 0, 8 };
		for (int i=0; i<number.length; i++) {
			try {
				System.out.println(number[i] + " / " +
				denom[i] + " is " + number[i]/denom[i]);
			}
			catch (ArithmeticException exc) {
				System.out.println("Can't divide by Zero!");
			}
			catch (ArrayIndexOutOfBoundsException exc) {
				System.out.println("No matching element found.");
			}
		}
	}
}

Download the code  Run the code

Output:

4 / 2 is 2
Can't divide by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divide by Zero!
128 / 8 is 16
No matching element found.
No matching element found.

We need to consider one important point when writing multiple catch blocks to a single try block,  which type is the subclass of which type. For example, we know that all exceptions are a subclass of Throwable type. then when we write two catch block with ArrayIndexOutOfBoundsException and Throwable, the order of catch blocks is very important. When an exception occurs Java check for catch block for the same type from top to bottom. If it matches then executes that catch block. In above case, if we write Throwable as first catch block and ArrayIndexOutOfBoundsException later, then our second block never executes because Throwable is a superclass of ArrayIndexOutOfBoundsException. Hence ArrayIndexOutOfBoundsException matches with first catch block and always the first block executes. This lead to unreachable code in our program and unreachable code in Java is an error.

/*
This is a simple Java program about Exception Handling.
Call this file KH_MaultipleCatch2.java.
*/

class KH_MaultipleCatch2 {
	public static void main(String args[]) {
		int number[] = { 4, 8, 16, 32, 64, 128, 256, 512 };
		int denom[] = { 2, 0, 4, 4, 0, 8 };
		for(int i=0; i<number.length; i++) {
			try {
				System.out.println(number[i] + " / " +
				denom[i] + " is " +
				number[i]/denom[i]);
			}
			catch (ArrayIndexOutOfBoundsException exc) {
				// catch the exception
				System.out.println("No matching element found.");
			}
			catch (Throwable exc) {
				System.out.println("Can't divide by Zero!");
			}
			
		}
	}
}

Download the code  Run the code

Output:

4 / 2 is 2
Can't divide by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divide by Zero!
128 / 8 is 16
No matching element found.
No matching element found.

Below is output if I swap two catch blocks.

KH_MaultipleCatch2.java:19: error: exception ArrayIndexOutOfBoundsException has
already been caught
                        catch (ArrayIndexOutOfBoundsException exc) {
                        ^
1 error

Nesting try blocks

It is possible to nest one try block into another try block. When an exception occurred in inner try block first its corresponding catch blocks will get executed. If this exception is not handled by inner try catch then it transfers to outer try catch blocks. In the below example, inner try catch blocks handle ArithmeticException and outer try catch block handles ArrayIndexOutOfBoundsException. The output of this program explains everything.

/*
This is a simple Java program about Exception Handling.
Call this file KH_Nestingtry.java.
*/

class KH_Nestingtry {
	public static void main(String args[]) {
		int number[] = { 4, 8, 16, 32, 64, 128, 256, 512 };
		int denom[]  = { 2, 0, 4, 4, 0, 8 };
		try {
			for(int i=0; i<number.length; i++) {
				try {
					System.out.println(number[i] + " / " +
					denom[i] + " is " +
					number[i]/denom[i]);
				}
				catch (ArithmeticException exc) {
					System.out.println("Can't divide by Zero!");
				}
			}
		}
		catch (ArrayIndexOutOfBoundsException exc) {
			System.out.println("No matching element found.");
		}
			
	}
}

Download the code  Run the code

Output:

4 / 2 is 2
Can't divide by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divide by Zero!
128 / 8 is 16
No matching element found.

In general practice, we use inner blocks to handle less complicated exceptions and the outer block is used to handle more severe and more complicated exceptions.

<<< Java Exception HandlingMethods in Throwable, Java’s Built-in Exceptions, and Custom Exception >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .