考虑到这段代码,我能绝对确定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");
}
当前回答
如果在嵌套的finally块中引发异常,finally也可以提前退出。编译器会警告你finally块没有正常完成,或者给出一个错误,说明你有无法访问的代码。仅当抛出不在条件语句后面或循环内部时,才会显示不可访问代码的错误。
try{
}finally{
try{
}finally{
//if(someCondition) --> no error because of unreachable code
throw new RunTimeException();
}
int a = 5;//unreachable code
}
其他回答
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”有权通过try重写任何异常/返回值。。捕捉块。例如,以下代码返回12:
public static int getMonthsInYear() {
try {
return 10;
}
finally {
return 12;
}
}
类似地,以下方法不会引发异常:
public static int getMonthsInYear() {
try {
throw new RuntimeException();
}
finally {
return 12;
}
}
虽然以下方法确实抛出了它:
public static int getMonthsInYear() {
try {
return 12;
}
finally {
throw new RuntimeException();
}
}
不,并非总是有一种例外情况//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将不执行:
案例1:
执行System.exit()时。
案例2:
当JVM/线程崩溃时。
案例3:
手动停止执行时。
最后总是在结尾处调用
当您尝试时,它会执行一些代码,如果在尝试中发生了什么,那么catch将捕获该异常,您可以打印一些mssg或抛出错误,然后最后执行块。
Finally通常在执行清理时使用,例如,如果使用java中的扫描仪,则可能应该关闭扫描仪,因为它会导致其他问题,例如无法打开某些文件