考虑到这段代码,我能绝对确定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");
}
考虑到这段代码,我能绝对确定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");
}
当前回答
不,并非总是有一种例外情况//System.exit(0);在finally块阻止finally被执行之前。
class A {
public static void main(String args[]){
DataInputStream cin = new DataInputStream(System.in);
try{
int i=Integer.parseInt(cin.readLine());
}catch(ArithmeticException e){
}catch(Exception e){
System.exit(0);//Program terminates before executing finally block
}finally{
System.out.println("Won't be executed");
System.out.println("No error");
}
}
}
其他回答
如果在嵌套的finally块中引发异常,finally也可以提前退出。编译器会警告你finally块没有正常完成,或者给出一个错误,说明你有无法访问的代码。仅当抛出不在条件语句后面或循环内部时,才会显示不可访问代码的错误。
try{
}finally{
try{
}finally{
//if(someCondition) --> no error because of unreachable code
throw new RunTimeException();
}
int a = 5;//unreachable code
}
Finally is always run这就是重点,只是因为它出现在返回后的代码中并不意味着它就是这样实现的。Java运行时有责任在退出try块时运行此代码。
例如,如果您有以下内容:
int foo() {
try {
return 42;
}
finally {
System.out.println("done");
}
}
运行时将生成如下内容:
int foo() {
int ret = 42;
System.out.println("done");
return 42;
}
如果抛出未捕获的异常,finally块将运行,异常将继续传播。
最后总是执行Block。除非和直到存在System.exit()语句(finally块中的第一条语句)。如果system.exit()是第一条语句,那么finally块将不会被执行,控制权将从finally块中释放出来。每当System.exit()语句进入finally块,直到该语句最终执行块,当System.exit)出现时,控制力完全从finally块中释放出来。
finally块总是在返回x(计算)值之前执行。
System.out.println("x value from foo() = " + foo());
...
int foo() {
int x = 2;
try {
return x++;
} finally {
System.out.println("x value in finally = " + x);
}
}
输出:
最终x值=3来自foo()的x值=2
最终将执行,这是肯定的。
在以下情况下,finally将不执行:
案例1:
执行System.exit()时。
案例2:
当JVM/线程崩溃时。
案例3:
手动停止执行时。