✏️ Explanatory Question

Can an exception be rethrown?

👁 35 Views
📘 Detailed Answer
🔴 Hard
💡

Answer with Explanation

Yes, an exception can be rethrown.
When an exception is caught inside a catch block, it can be thrown again to be handled by another method (usually the caller method).
This process continues up the call stack until a method is found that can handle the exception properly.

Example:


try {
    try {
        int a = 5 / 0;
    } 
    catch (ArithmeticException e) {
        System.out.println("Rethrowing exception...");
        throw e; // rethrowing the same exception
    }
}
catch (ArithmeticException e) {
    System.out.println("Handled in outer catch block.");
}

Output:


Rethrowing exception...
Handled in outer catch block.