Exception Handling in Java: Unraveling the Ambiguity
In a puzzling Java exception-handling scenario, a university question presented the following code snippet:
// Exception Heirarchy
class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
// Main Class
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print(1);
q();
}
catch (Exception i) {
throw new MyExc2();
}
finally {
System.out.print(2);
throw new MyExc1();
}
}
static void q() throws Exception {
try {
throw new MyExc1();
}
catch (Exception y) {
}
finally {
System.out.print(3);
throw new Exception();
}
}
}
The question asked for its output, and the answer provided was "13Exception in thread main MyExc2". However, the correct answer is "132Exception in thread main MyExc1".
Clarifying the Ambiguity
To decipher this puzzle, it's essential to understand the precedence of exceptions:
Consequences:
Retracing the Execution
Applying this principle to the code:
Initial Execution:
Catch Block Exception:
Execution Resumes in Main's Try Block:
Finally Block Exception:
Output:
The final output is "132Exception in thread main MyExc1" because the exception that propagates out of the main method is the MyExc1 thrown in line 16. The MyExc2 thrown in line 19 is aborted when MyExc1 is thrown in line 16.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3