Propagating Exceptions Example
This program demonstrates exception propagation across methods.
Problem Statement
Write a Java program where an exception is thrown in one method and propagated to the caller.
Source Code
| 1 | public class ExceptionPropagationExample { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Exception Propagation Example"); |
| 4 | try { |
| 5 | method1(); |
| 6 | } catch(Exception e) { |
| 7 | System.out.println("Eduinq Exception Handled in Main: "+e.getMessage()); |
| 8 | } |
| 9 | } |
| 10 | static void method1() throws Exception { |
| 11 | method2(); |
| 12 | } |
| 13 | static void method2() throws Exception { |
| 14 | throw new Exception("Eduinq Exception Propagated"); |
| 15 | } |
| 16 | } |
Program Output
Eduinq Exception Propagation Example Eduinq Exception Handled in Main: Eduinq Exception Propagated
Explanation
Exception thrown in method2 propagates to method1 and then to main. - Caller must handle or declare the exception. - This design improves modularity and error management. - In enterprise systems, propagation ensures centralized handling of errors. Conclusion: Shows exception propagation across methods.