java里面try会循环吗_关于Java:在try循环中使用try-finally块

本问题已经有最佳答案,请猛点这里访问。

当我在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谢谢,不知道。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值