当 try 语句和 finally 语句中都有 return 语句时,在⽅法返回之前,finally 语句的内容将被 执⾏,并且 finally 语句的返回值将会覆盖原始的返回值。
/**
* @author wsq
* @date 2021/1/16
*/
public class TryCatchTest {
public static void main(String[] args) {
int ans = f(2);
System.out.println(ans);
}
private static int f(int value){
try {
// value会执行,证明这条语句能够执行
return value++;
}finally {
return value;
}
}
}
output:
3
本文通过一个示例代码展示了在Java中,当try-catch块和finally块都包含return语句时,finally块的返回值会覆盖try块的返回值。这个例子演示了finally块在方法返回前的执行优先级,对于理解Java异常处理机制和return语句的行为具有重要意义。
3190





