Nested Try-Catch Example
This program demonstrates nested try-catch blocks.
Problem Statement
Write a Java program that uses nested try-catch to handle multiple risky operations.
Source Code
| 1 | public class NestedTryCatchExample { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Nested Try-Catch Example"); |
| 4 | try { |
| 5 | int[] arr=new int[3]; |
| 6 | try { |
| 7 | int result=10/0; |
| 8 | System.out.println("Eduinq Result: "+result); |
| 9 | } catch(ArithmeticException e) { |
| 10 | System.out.println("Eduinq Inner Exception: Division by zero"); |
| 11 | } |
| 12 | arr[5]=20; |
| 13 | } catch(ArrayIndexOutOfBoundsException e) { |
| 14 | System.out.println("Eduinq Outer Exception: Array Index Error"); |
| 15 | } |
| 16 | } |
| 17 | } |
Program Output
Eduinq Nested Try-Catch Example Eduinq Inner Exception: Division by zero Eduinq Outer Exception: Array Index Error
Explanation
Nested try-catch allows handling exceptions at different levels. - Inner block handles arithmetic errors, outer block handles array errors. - This design improves granularity in error handling. - It ensures specific handling for different risky operations. - In enterprise systems, nested try-catch improves robustness in complex workflows. Conclusion: Shows nested try-catch exception handling.