Rethrow Exception Example
This program demonstrates rethrowing exceptions.
Problem Statement
Write a Java program that catches an exception and rethrows it for higher-level handling.
Source Code
| 1 | public class RethrowExceptionExample { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Rethrow Exception Example"); |
| 4 | try { |
| 5 | riskyOperation(); |
| 6 | } catch(Exception e) { |
| 7 | System.out.println("Eduinq Exception Handled at Main: "+e.getMessage()); |
| 8 | } |
| 9 | } |
| 10 | static void riskyOperation() throws Exception { |
| 11 | try { |
| 12 | throw new Exception("Eduinq Risk Detected"); |
| 13 | } catch(Exception e) { |
| 14 | System.out.println("Eduinq Exception Handled Locally"); |
| 15 | throw e; |
| 16 | } |
| 17 | } |
| 18 | } |
Program Output
Eduinq Rethrow Exception Example Eduinq Exception Handled Locally Eduinq Exception Handled at Main: Eduinq Risk Detected
Explanation
Rethrowing allows exceptions to be handled at multiple levels. - Local catch block logs the error, then rethrows it. - Main method handles the rethrown exception. - This design improves error propagation and logging. - In enterprise systems, rethrowing ensures centralized error handling. Conclusion: Shows rethrowing exceptions for higher-level handling.