Multiple try and Catch

Multiple catch Clauses

In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed.

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

Nested try Statements

One try block can be nested within another. An exception generated within the inner try block that is not caught by a catch associated with that try is propagated to the outer try block. For example, here the ArrayIndexOutOfBoundsException is not caught by the inner catch, but by the outer catch.

public class NestedTryExample {
	public static void main(String args[]) {
		// Here, numer is longer than denom.
		int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 };
		int denom[] = { 2, 0, 4, 4, 0, 8 };
		try { // outer try
			for (int i = 0; i < numer.length; i++) {
				try { // nested try
					System.out.println(numer[i] + " / " + denom[i] + " is " +
                                        numer[i] / denom[i]);
				} catch (ArithmeticException exc) {
					// catch the exception
					System.out.println("Can't divide by Zero!");
				}
			}
		} catch (ArrayIndexOutOfBoundsException exc) {
			// catch the exception
			System.out.println("No matching element found.");
			System.out.println("Fatal error – program terminated.");
		}
	}
}