Exception handling is a crucial concept in Java, ensuring that runtime errors don’t crash the program. Java provides the try-catch
mechanism to handle exceptions gracefully. Sometimes, handling exceptions requires more than just a single try-catch
block, leading to nested try-catch blocks.
A nested try-catch block is a try
block inside another try
block. This structure allows handling exceptions at multiple levels, providing more precise error handling.
- Handling different exceptions at different levels: Some exceptions may need to be handled immediately, while others can be escalated.
- Ensuring specific operations are protected: Certain code segments may require individual exception handling within a larger context.
- Providing fine-grained control over exception handling: This improves debugging and makes code more robust.
Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class NestedTryExample { public static void main(String[] args) { try { System.out.println("Outer try block"); try { int num = 10 / 0; // This will cause ArithmeticException System.out.println("This won't execute"); } catch (ArithmeticException e) { System.out.println("Inner catch: ArithmeticException handled"); } int arr[] = {1, 2, 3}; System.out.println(arr[5]); // This will cause ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Outer catch: ArrayIndexOutOfBoundsException handled"); } System.out.println("Program continues..."); } } |
Output
1 2 3 4 |
Outer try block Inner catch: ArithmeticException handled Outer catch: ArrayIndexOutOfBoundsException handled Program continues... |
- The outer
try
block contains two risky operations. - The inner
try
block attempts a division by zero, which throws anArithmeticException
. - The inner
catch
block catches theArithmeticException
and handles it. - Execution continues in the outer
try
block, where an attempt to access an invalid array index throws anArrayIndexOutOfBoundsException
. - The outer
catch
block handles this exception, ensuring the program doesn’t crash.