本问题已经有最佳答案,请猛点这里访问。
当我在while循环中最终使用时,我试图了解该机制。
在下面的代码中。 最后行打印,然后休息。 我期望代码不会到达finally块。 或者,如果到达了finally块,则没有中断,因此应该继续。.有人可以解释它的工作原理吗?
while(true){
System.out.println("in while");
try{
break;
}finally{
System.out.println("in finally");
}
}
System.out.println("after while");
输出是
in while
in finally
after while
尽管您break可以确保始终在尝试执行时最终获得执行。 您不能停止最终进入控件。
https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
这种行为是有原因的。 它对我们有帮助。
it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
简而言之,无论您在try内部执行任何操作以退出当前循环或函数,都会执行finally。 这对于任何return,break,continue以及几乎所有其他可能导致您到达任何地方的情况都是如此:try(通常)只能保留通过finally。
但是,也有例外:正如OldCurmudgeon所指出的那样,System.exit()确实可以成功执行,但不能使finally被执行。
很少有例外-System.exit(n)避免使用final。
@OldCurmudgeon谢谢,不知道。