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.

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...