Java – Nested try-catch block in Exception handling

In this article, we will discuss nesting of try-catch block inside another try-catch block in Java Exception handling

1. Nested try-catch block:

  • When try-catch block reside/present inside another try-block, it is called as nesting of try-catch block

Pseudo code:

// Outer try-catch block
try {

	try {
		// Inner try-catch block
	}
	catch(RuntimeException rtex) {
		rtex.printStackTrace();
	}
}
catch(Exception ex) {
	ex.printStackTrace();
}

Q) Why we need to nest try-catch block inside another try-catch combination ?

  • When part of code inside try-catch block might raise exception, then in this case it is better to handle exception with another try-catch block inside outer try-catch block

NestedTryCatchBlock.java

package in.bench.resources.exception.handling;

public class NestedTryCatchBlock {

	public static void main(String[] args) {

		// Outer try-catch block
		try {
			System.out.println("Statment ABOVE"
					+ " nested try-catch block");

			try {
				// Inner try-catch block
				int result = 18/0;
				System.out.println("The result of division : "
						+ result);
			}
			catch(ArithmeticException aex) {
				aex.printStackTrace();
			}
			System.out.println("Statment BELOW"
					+ " nested try-catch block");
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}

Explanation:

In the above nested try-catch block example,

  • Assumption: code above & below nested try-catch block works/executes fine without any exception
  • But code inside nested try-block might raise arithmetic exception, as it is performing division by zero operation
  • In this case, it is better handle exception inside nested try-catch block
  • And in the outer try-catch blocks, other exceptions can be handled

2. Nesting try-catch block :

It can be nested inside another

  • try block
  • catch block
  • finally block
  • Note: try-catch block combination can be nested inside outer try-catch-finally blocks

2.1 Pseudo code – nested try-catch inside try-block:

// Outer try-catch block
try {

	try {
		// Inner try-catch block
	}
	catch(ArithmeticException aex) {
		aex.printStackTrace();
	}
	finally {
		// finally always gets executed
	}
}
catch(Exception ex) {
	ex.printStackTrace();
}

2.2 Pseudo code – nested try-catch inside catch-block:

// Outer try-catch block
try {

}
catch(Exception ex) {

	// nested inside catch block
	try {
		// Inner try-catch block
	}
	catch(ArithmeticException aex) {
		aex.printStackTrace();
	}
	finally {
		// finally always gets executed
	}
}

2.3 Pseudo code – nested try-catch inside finally block:

// Outer try-catch block
try {

}
catch(Exception ex) {
	ex.printStackTrace();
}
finally {
	// finally always gets executed

	// nested inside finally block
	try {
		// Inner try-catch block
	}
	catch(ArithmeticException aex) {
		aex.printStackTrace();
	}
	finally {
		// finally always gets executed
	}
}

Q) How long/deep nesting can be done ?

  • Nesting can be done at any level
  • but 2-level nesting is considered as a good programming practice
  • provided it is justifiable from programming point of view

Q) What happens, if inner nested try-catch block raises exception but didn’t caught in the nested catch-block ?

  • The only reason nested try-catch blocks doesn’t catch exception is because we haven’t provided respective catch-block (to catch that particular exception-type)
  • In this case, outer try-catch blocks is checked for catch-block with corresponding exception-type is available or NOT
  • If available, then it is caught in the outer catch-block and exception handler-code gets executed and program terminates normally i.e.; graceful termination
  • Otherwise, it is handled by JVM which results into termination of program abruptly i.e.; abnormal termination

3. Nesting try-catch block examples:

  1. Exception is handled inside INNER catch-block
  2. Exception is handled inside OUTER catch-block
  3. Exception is neither handled in INNER catch-block nor OUTER catch-block

Let us see a full-fledged example for few cases:

3.1 Nested try-catch block where exception is handled inside inner catch-block (i.e.; nested catch block)

  • exception is raised/thrown from inner try-catch block and
  • it is caught in the inner nested try-catch block ONLY

NestedTryCatchBlock.java

package in.bench.resources.exception.handling;

public class NestedTryCatchBlock {

	public static void main(String[] args) {

		// Outer try-catch block
		try {

			System.out.println("Outer try-catch block");

			// nested inside finally block
			try {
				// Inner try-catch block

				String str = null;
				System.out.println("Lenght of string is : "
						+ str.length());
			}
			catch(NullPointerException npex) {
				System.out.println(npex.toString());
			}
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
		finally {
			// finally block always gets executed
			System.out.println("finally block"
					+ " always gets executed");
		}
	}
}

Output:

Outer try-catch block
java.lang.NullPointerException
finally block always gets executed

Explanation:

  • Nested try-block raises a null-pointer exception which get caught in the inner catch-block and respective exception information gets printed in the console
  • In this example, catch-block just simply prints exception information but in real-time scenario we can provide alternate handler-code for any exception raised
  • When this program is coded in Eclipse IDE, it warns programmer with message stating “Null pointer access: The variable str can only be null at this location
  • It is wise to listen to compiler for this warning and take corrective actions even before trying to execute

Screen capture from Eclipse IDE:

3.2 Nested try-catch block where exception is NOT handled inside nested try-catch block (i.e.; handled in outer catch-block)

  • exception is raised from nested try-catch block
  • but it is handled in outer try-catch block

NestedTryCatchBlockExceptionNotHandled.java

package in.bench.resources.exception.handling;

public class NestedTryCatchBlockExceptionNotHandled {

	public static void main(String[] args) {

		// Outer try-catch block
		try {

			System.out.println("Outer try-catch block");

			// nested inside finally block
			try {
				// Inner try-catch block

				String str = null;
				System.out.println("Lenght of string is : "
						+ str.length());
			}
			catch(NumberFormatException nfex) {
				System.out.println(nfex.toString());
			}
		}
		catch(NullPointerException npex) {
			System.out.println(npex.toString());
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
		finally {
			// finally block always gets executed
			System.out.println("finally block"
					+ " always gets executed");
		}
	}
}

Output:

Outer try-catch block
java.lang.NullPointerException
finally block always gets executed

Explanation:

  • In this example, exception is raised from nested try-block but it doesn’t get caught in the nested catch-block
  • Because there is no corresponding catch-block for this exception-type
  • Therefore, its looks for corresponding exception-type in the outer try-catch block
  • Since, it finds the matching catch-block with this exception-type, therefore it caught in the outer catch-block and respective handler-code gets executed
  • Note: rest remain same for outer try-catch blocks i.e.; if any exception raised from outer try-block then corresponding catch-block catches this exception with this exception-type

Screen capture from Eclipse IDE:

3.3 Nested try-catch block where exception is NOT handled either inside nested try-catch block nor outer try-catch blocks

  • exception is raised from nested try-catch block
  • but it is neither handled in inner try-catch block nor handled in outer try-catch block

NestedTryCatchBlockExceptionNotHandledInsideAndOutside.java

package in.bench.resources.exception.handling;

public class
NestedTryCatchBlockExceptionNotHandledInsideAndOutside {

	public static void main(String[] args) {

		// Outer try-catch block
		try {

			System.out.println("Outer try-catch block");

			// nested inside finally block
			try {
				// Inner try-catch block

				char[] ch = new char[4];
				System.out.println("The value"
						+ " at 7th position is : " + ch[7]);
			}
			catch(NumberFormatException nfex) {
				System.out.println(nfex.toString());
			}
		}
		catch(ClassCastException ccex) {
			System.out.println(ccex.toString());
		}
		catch(NullPointerException npex) {
			System.out.println(npex.toString());
		}
		finally {
			// finally block always gets executed
			System.out.println("finally block"
					+ " always gets executed");
		}
	}
}

Output:

Outer try-catch block
finally block always gets executed
Exception in thread "main"
	java.lang.ArrayIndexOutOfBoundsException: 7
	at in.bench.resources.exception.handling
	.NestedTryCatchBlockExceptionNotHandledInsideAndOutside.main(
NestedTryCatchBlockExceptionNotHandledInsideAndOutside.java:17)

Explanation:

  • In this example, ArrayIndexOutOfBoundsException is thrown from nested try-block but there isn’t any corresponding catch-block for handling this exception-type
  • Hence, this exception is inspected in the outer catch-block for matching exception-type
  • Even there isn’t any matching catch-block for handling this exception-type
  • Therefore, JVM handles this exception by passing control to Default exception handler along with exception object created method, which prints exception stack trace in the console & terminates program abnormally

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Returning value from method having try-catch-finally blocks
Java - try with multiple catch-block