考虑到这一点的代码,我可以绝对肯定的是,finally块总是执行,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
Run Code Online (Sandbox Code Playgroud) 我知道涉及在try/catch/finally块中返回的令人头痛的问题 - finally中的返回始终是方法的返回,即使try或catch块中的返回应该是执行的返回.
但是,同样适用于System.exit()?例如,如果我有一个try块:
try {
//Code
System.exit(0)
}
catch (Exception ex) {
//Log the exception
}
finally {
System.exit(1)
}
Run Code Online (Sandbox Code Playgroud)
如果没有异常,将调用哪个System.exit()?如果exit是return语句,则System.exit(1)行将始终(?)被调用.但是,我不确定退出的行为是否与返回不同.
代码处于极端情况下,即使不是不可能,也很难重现,因此我无法编写单元测试.我今天晚些时候会尝试进行一项实验,如果我得到一些免费的分钟,但我很好奇,也许有人知道答案,可以提供它,或者我无法运行实验.