java - 在 while 循环中使用 try-finally block

标签 java while-loop break try-finally

<分区>

当我在 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.

关于java - 在 while 循环中使用 try-finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48681988/

相关文章:

java - 比较器 - int 不能取消引用

java - 测试先前声明的变量总和是否不等于 3.14 的 boolean 表达式

java - Android Studio,未找到 JVM 安装

python - 如何只接受3-8之间的整数而不接受字符串? (Python 2.7.5)

php - 如何优化 SQL 查询以避免 while() 嵌套子查询?

HTML、CSS - 长表的换行符需要修复

java - 如何在 Java 中以编程方式解析 PKCS12 文件?

php foreach循环用几个词搜索mysql表

Bash 通过用户输入中断 while 循环

java - java中如何限制用户输入一定范围内的数字?