Rak*_* KR 38 java finally try-catch-finally
我们可以在finally块中使用return语句.这会导致任何问题吗?
Ank*_*thi 46
从finally块内返回将导致exceptions丢失.
finally块中的return语句将导致可能在try或catch块中抛出的任何异常被丢弃.
如果try块的执行由于任何其他原因R突然完成,则执行finally块,然后有一个选择:
Run Code Online (Sandbox Code Playgroud)If the finally block completes normally, then the try statement completes abruptly for reason R. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
注意:根据JLS 14.17 - 返回语句总是突然完成.
Kru*_*hna 27
是的,您可以在finally块中编写return语句,它将覆盖其他返回值.
编辑:
例如在下面的代码中
public class Test {
public static int test(int i) {
try {
if (i == 0)
throw new Exception();
return 0;
} catch (Exception e) {
return 1;
} finally {
return 2;
}
}
public static void main(String[] args) {
System.out.println(test(0));
System.out.println(test(1));
}
}
Run Code Online (Sandbox Code Playgroud)
输出总是2,因为我们从finally块返回2.记住,finally总是执行是否存在异常.所以当finally块运行时,它将覆盖其他的返回值.在finally块中编写return语句不是必需的,实际上你不应该写它.
| 归档时间: |
|
| 查看次数: |
40308 次 |
| 最近记录: |