Wrapping Exceptions Example
This program demonstrates wrapping exceptions inside another exception.
Problem Statement
Write a Java program that wraps a low-level exception inside a custom exception.
Source Code
| 1 | class EduinqWrappedException extends Exception { |
| 2 | public EduinqWrappedException(String msg, Throwable cause){ super(msg,cause); } |
| 3 | } |
| 4 | public class ExceptionWrappingExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Exception Wrapping Example"); |
| 7 | try { |
| 8 | riskyOperation(); |
| 9 | } catch(EduinqWrappedException e) { |
| 10 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 11 | System.out.println("Eduinq Cause: "+e.getCause()); |
| 12 | } |
| 13 | } |
| 14 | static void riskyOperation() throws EduinqWrappedException { |
| 15 | try { |
| 16 | int result=10/0; |
| 17 | } catch(ArithmeticException e) { |
| 18 | throw new EduinqWrappedException("Eduinq Wrapped Exception", e); |
| 19 | } |
| 20 | } |
| 21 | } |
Program Output
Eduinq Exception Wrapping Example Eduinq Exception: Eduinq Wrapped Exception Eduinq Cause: java.lang.ArithmeticException: / by zero
Explanation
Wrapping exceptions preserves original cause while adding context. - Improves clarity and debugging. - Provides layered error information. - In enterprise systems, wrapping ensures meaningful error propagation. Conclusion: Shows wrapping exceptions with custom context.