当我在 while 循环中使用 finally 时,我试图理解该机制。
在下面的代码中。 In finally 行打印,然后 while 中断。我期望代码不会到达 finally block 。或者,如果它到达 finally block ,那里没有中断,所以 while 应该继续。任何人都可以解释这是如何工作的吗?
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
可以保证在执行 try 时总是 finally 执行。你无法停止进入 finally 控件。
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.