Nested try blocks in Exception Handling in Java
Last Updated :
24 Mar, 2025
In Java, we can use a try block within another try block. This is called nested try blocks. Each time a try statement is entered, the context of that exception is pushed onto a stack. If an exception occurs in the inner try block and is not caught by its corresponding catch block, the exception propagates to the outer try block. This process continues until the exception is either caught or reaches the default exception handler.
- Nested try blocks are useful for handling exceptions at different levels of code.
- If an exception occurs in a parent try block, the control jumps directly to the matching catch block in the parent or outer try block, and any nested try blocks are skipped.
- If an exception occurs in an inner try block and is not caught, it propagates to the outer try block.
Basic Nested Try Blocks
Example 1: This example demonstrates nested try-catch blocks, where an ArrayIndexOutOfBoundsException is caught in the outer block, and an ArithmeticException is handled in the inner block.
Java
class Geeks {
// Main method
public static void main(String args[]) {
// Main try block
try {
// Initializing array
int a[] = { 1, 2, 3, 4, 5 };
// Trying to print element at index 5
System.out.println(a[5]);
// Inner try block (try-block2)
try {
// Performing division by zero
int x = a[2] / 0; // This will throw ArithmeticException
} catch (ArithmeticException e2) {
System.out.println("Division by zero is not possible");
}
} catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exist");
}
}
}
OutputArrayIndexOutOfBoundsException
Element at such index does not exist
Explanation: The outer try block attempts to access an element at index 5 of the array a[], which throws an ArrayIndexOutOfBoundsException. Since the exception occurs in the outer try block, the control immediately jumps to the corresponding catch block (catch (ArrayIndexOutOfBoundsException e1)). The inner try block is never executed because the exception in the outer block interrupts the flow. Therefore, the message "Division by zero is not possible" is not printed.
Why "division by zero is not possible" not printed on the Screen?
The exception (ArrayIndexOutOfBoundsException) occurs in the outer try block. When an exception occurs in a parent try block, the control immediately jumps to the matching catch block in the parent or outer try block. The inner try block is never executed because the exception in the outer block interrupts the flow.
Multiple Levels of Nested Try Blocks
Example 2: This example demonstrates multiple levels of nested try-catch blocks, where an ArrayIndexOutOfBoundsException is caught in the outermost block, and inner blocks handle specific exceptions.
Java
class Geeks {
// Main method
public static void main(String args[]) {
// Main try block
try {
// try-block2
try {
// try-block3
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" try-block1");
}
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" try-block2");
}
} catch (ArrayIndexOutOfBoundsException e4) {
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" main try-block");
} catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
OutputArrayIndexOutOfBoundsException main try-block
Explanation:
The innermost try block (try-block3) attempts to access an element at index 10 of the array arr[], which throws an ArrayIndexOutOfBoundsException. Since there is no matching catch block for ArrayIndexOutOfBoundsException in the innermost try block, the exception propagates to the next outer try block (try-block2). The try-block2 also does not have a matching catch block for ArrayIndexOutOfBoundsException, so the exception propagates further to the outermost try block. The outermost try block has a matching catch block for ArrayIndexOutOfBoundsException, so the control jumps to this block and executes the corresponding code.
Note: If an exception occurs in a parent try block, the control jumps directly to the matching catch block in the parent or outer try block, and any nested try blocks are skipped.
Similar Reads
Best Practices to Handle Exceptions in Java Exception Handling is a critical aspect of Java programming, and following best practices for exception handling becomes even more important at the industry level, where software is expected to be highly reliable, maintainable, and scalable. In this article, we will discuss some of the best practice
7 min read
Exception Handling with Method Overriding in Java In Java, an exception is an unwanted or unexpected event that occurs during a program's execution, i.e., at runtime, and disrupts the normal flow of the programâs instructions. Exception handling in Java handles runtime errors and helps maintain the program's normal flow by using constructs like try
5 min read
Java - Exception Handling With Constructors in Inheritance Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then th
7 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Comparison of Exception Handling in C++ and Java Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.W
4 min read
Errors V/s Exceptions In Java In Java, errors and exceptions are both types of throwable objects, but they represent different types of problems that can occur during the execution of a program. Errors are usually caused by serious problems that are outside the control of the program, such as running out of memory or a system cr
5 min read
How to Solve Class Cast Exceptions in Java? An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote fi
3 min read
Output of Java program | Set 12(Exception Handling) Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? Java public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticExcept
3 min read
Built-in Exceptions in Java with examples Types of Exceptions in Java Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. Examples of Built-in Exception:1. Arithmetic exception : It is throw
8 min read
User-Defined Custom Exception in Java In Java, an Exception is an issue (run-time error) that occurs during the execution of a program. When an exception occurs, the program terminates abruptly, and the code beyond the exception never gets executed.Java provides us the facility to create our own exceptions by extending the Exception cla
3 min read