加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在循环中使用try-finally块

发布时间:2020-12-15 01:08:51 所属栏目:Java 来源:网络整理
导读:参见英文答案 Does a finally block always get executed in Java?????????????????????????????????????46个 我试图理解当我最终在while循环中使用时的机制. 在下面的代码中.在最后的行打印和比休息时间.我期待代码不会到达finally块.或者,如果它到达finall

参见英文答案 > Does a finally block always get executed in Java?????????????????????????????????????46个
我试图理解当我最终在while循环中使用时的机制.
在下面的代码中.在最后的行打印和比休息时间.我期待代码不会到达finally块.或者,如果它到达finally块,那里就没有中断,所以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
最佳答案
虽然你打破了它,但保证在尝试执行时总是最终执行.你不能最终停止进入控制.

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,or break.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读