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

前端之家收集整理的这篇文章主要介绍了java – 在循环中使用try-finally块前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > 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.

@H_403_41@ 原文链接:https://www.f2er.com/java/437473.html

猜你在找的Java相关文章