In Java, it is allowed to have a try block inside another try block, which is known as a nested try block. Whenever a statement is enclosed in a try block, the context of that exception is stacked.
One way to demonstrate this is by utilizing the inner try block to manage situations involving ArrayIndexOutOfBoundsException, whereas the outer try block can address occurrences of ArithmeticException, such as division by zero.
Why use nested try blocks?
Occasionally, a scenario might occur where a segment within a block triggers one error while the entire block results in another error. In such instances, it becomes necessary to nest exception handlers.
Syntax:
try {
// Outer try block
try {
// Inner try block
} catch (ExceptionType1 e1) {
// Inner catch block
}
} catch (ExceptionType2 e2) {
// Outer catch block
}
Nested try Block Examples
Example: Handling Two Different Exceptions
Consider an instance where we nest a try block inside another try block to handle two distinct exceptions.
Example
public class Main {
public static void main(String args[])
{
//outer try block
try {
//inner try block 1
try {
System.out.println("cannot divide by 0");
int b =39/0;
}
//catch block of the inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of the inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of the outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
cannot divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..
If a try block does not contain a catch block for a specific exception, the catch block of the surrounding (parent) try block is evaluated for that exception. If the exception matches, the catch block of the outer try block is triggered.
If no catch blocks in the provided code can manage the exception, the Java runtime system will take care of it and show the default message associated with that exception.
Example: Handling Exception by the Main try Block
Let's explore the scenario illustrated here. In this case, the try block inside the nested try block (inner try block 2) does not manage the exception. Subsequently, the program flow moves to its enclosing try block (inner try block 1). If this block also fails to handle the exception, the flow proceeds to the primary try block (outer try block), where the suitable catch block deals with the exception. This situation is known as nesting.
Example
public class Main {
public static void main(String args[])
{
// outer (main) try block
try {
//inner try block 1
try {
// inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };
//printing the array element out of its bounds
System.out.println(arr[10]);
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Upon running the program mentioned above, the following exception is thrown:
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 4 outer (main) try block
Advantages of Nested try Blocks
- Enables more thorough handling of exceptions inside designated code segments.
- It is helpful when we wish to handle distinct exceptions that may be thrown by various parts of a block independently.
- It enhances readability and debugging by keeping exception handling near the code that may throw it.
- Deep nesting, particularly in large programs, can make the code difficult to read and comprehend.
- When try-catch blocks are deeply nested, it becomes more difficult to track the execution flow and handle exceptions.
- Code with numerous nested try blocks can be difficult to debug or refactor, and it can take a lot of time.
- Promotes Poor Structure: If used extensively, it may result in poor coding techniques rather than breaking up code into more digestible, smaller chunks.
- Nested try blocks allow handling exceptions at different levels. The inner try block catches specific exceptions first, while the outer try block handles broader exceptions.
- If an exception occurs in the inner try block and is not caught, it propagates to the outer catch block.
- Each try block (inner or outer) can have multiple catch blocks to handle different types of exceptions separately.
- The child catch block can handle specific exceptions, while the parent catch block can handle more generic ones. There is no strict rule on the exception hierarchy between them.
- If an exception is handled in the inner catch block, execution continues normally. If not, it moves to the outer catch block.
- Use specific exceptions in the inner catch block for better clarity.
- The outer catch block should handle broader exceptions to ensure robustness.
Disadvantages of Nested try Blocks
Important Points to Remember
Best Practices
Java Nested try blocks MCQs
- What is a nested try block in Java?
- A method to handle multiple exceptions
- A try block inside another try block
- A type of loop structure
- None of the above
Explanation: In Java, using a try block inside another try block is permitted. It is called a nested try block.
- What happens if an exception is thrown in the inner try block?
- The inner catch block catches it
- The outer catch block catches it
- Both inner and outer catch blocks will execute
- It will terminate the program
Explanation : Option 1 is correct in case if the exception is handled. If the try block within the nested try block (inner try block 2) does not handle the exception, the control is then transferred to its parent try block (inner try block 1). If it does not handle the exception, then the control is transferred to the main try block (outer try block), where the appropriate catch block handles the exception.
- Can we have multiple catch blocks for a nested try block?
- Only one catch block is allowed
- Only if the outer try block has catch blocks
Explanation: Yes, a nested try-catch block can have multiple catch blocks, just like a regular try-catch block. Each catch block in the nested try-catch can handle a specific type of exception thrown within that particular try block.
- Which of the following is true about nested try blocks?
- They improve code readability
- They help in handling exceptions effectively
- They can make debugging more complex
- All of the above
Explanation: Nested try blocks improve code readability, handling exceptions, and can make debugging more complex.
- Is it mandatory to have a catch block for every try block?
- Only for the outer try block
- Only for the inner try block
It is not obligatory to include a catch block immediately after every try block. Following a try block, it is acceptable to have a catch block, a finally block, or both. In cases where a catch block is absent, a finally block becomes necessary.