In normal situation this is how we use the try-catch-finally statement:
try {
//Code
}catch (Exception e) {
//Handle the exceptional case
}finally {
//Clean up code to be executed no matter there are exceptions
}
This is how I understand how JVM execute the statements.
1. If try block completes normally with a return statement, the finally block will be executed before executing the return statement in try block.
2. If try block completes aburptly with an exception that could be catched by the catch block, catch block will be executed. In this case:
2.1 If the catch block completes normally with a return statement, the finally block will be executed before executing the return statement in catch block
2.2 If the catch block completes aburptly with an exception, finally block will be executed before throwing a new exception in catch block.
Base on the assumption, that explains why the throw statement is not executed in catch block:
package com.ricardo.test.trycatchblock;
public class Test {
public static void main(String[] args) {
System.out.println(getResult(0));
}
public static int getResult(int b) {
int result = -1;
try {
result = 100 / b;
}catch (ArithmeticException e) {
result = -2;
throw new RuntimeException("Ricardo defined Exception");
}finally {
return result;
}
}
}
When there is an ArithmeticException thrown in the try block, the catch block is executed. When it reaches the throw statement, JVM starts executing the finally block before throw a "Ricardo defined Exception" RuntimeException. However, the return statement in finally block directly return the value to main method, so eventually the throw statement is not executed.

If I move the return statement out of finally block,
package com.ricardo.test.trycatchblock;
public class Test {
public static void main(String[] args) {
System.out.println(getResult(0));
}
public static int getResult(int b) {
int result = -1;
try {
result = 100 / b;
}catch (ArithmeticException e) {
result = -2;
throw new RuntimeException("Ricardo defined Exception");
}finally {
}
return result;
}
}
the exception can be thrown. Also if you are using intellij, there is a hint as below:

Reference:
Java Language Specification: https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2
本文深入探讨了Java中try-catch-finally语句的执行机制,解析了在不同情况下(如正常返回、捕获异常及抛出新异常)finally块的执行时机。并通过具体代码示例,展示了当finally块中包含return语句时,如何影响异常的抛出过程。
709

被折叠的 条评论
为什么被折叠?



