Exception Propagation in Catch and Finally Blocks
In a Java program, when an exception occurs, it propagates through the stack until it is handled by a suitable catch block or terminates the program. However, exceptions can also be thrown within catch or finally blocks, raising questions about their propagation behavior.
Consider the following code snippet:
<code class="java">class MyExc1 extends Exception {} class MyExc2 extends Exception {} class MyExc3 extends MyExc2 {} public class C1 { public static void main(String[] args) throws Exception { try { System.out.print(1); q(); } catch (Exception i) { throw new MyExc2(); // Exception thrown in catch block } finally { System.out.print(2); throw new MyExc1(); // Exception thrown in finally block } } static void q() throws Exception { try { throw new MyExc1(); } catch (Exception y) { } finally { System.out.print(3); throw new Exception(); // Exception thrown in finally block } } }</code>
When an exception is thrown within a catch or finally block, the following principle applies:
Exception Overriding: If a new exception is thrown within a catch or finally block that is intended to propagate out of that block, the current exception in progress will be aborted, and the new exception will propagate outward, taking its place. The aborted exception will be discarded.
In the provided code, the exception scenario in both the catch and finally blocks demonstrates this principle:
Consequently, when the program execution reaches the main method after unwinding the stack, the MyExc2 exception has been overridden by MyExc1, which is subsequently printed and handled. Hence, the correct output is "132Exception in thread main MyExc1."
The above is the detailed content of How does exception propagation work when exceptions are thrown within catch and finally blocks in Java?. For more information, please follow other related articles on the PHP Chinese website!