在while循环中使用try-finally块 [英] Using try-finally block inside while loop

查看:251
本文介绍了在while循环中使用try-finally块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在while循环中最终使用时,我试图理解该机制. 在下面的代码中. 最后行打印,然后休息一会儿.我期望代码不会到达finally块.或者,如果到达了finally块,那么这里没有没有中断,因此应该继续..有人可以解释它是如何工作的吗?

I am trying to understand the mechanism when i use finally inside a while loop. In the below code. In finally line prints and than the while breaks. I was expecting the code not to reach the finally block. Or if it reaches the finally block, there is no break there so the while should continue.. Can anyone explain how this works ?

         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可以确保在尝试执行时始终总能得到执行.您不能停止最后进入控件.

Although you break it is guaranteed that always finally gets execute when try executed. You can't stope entering the control into finally.

https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

try块退出时,finally块始终执行.这样可以确保即使发生意外异常,也可以执行finally块.但是,最后,它不仅对异常处理有用,它还使程序员避免因返回,继续或中断而意外跳过清理代码.

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.

此行为是有原因的.它对我们有帮助.

There is a reason for the behaviour. It help us.

它允许程序员避免清理代码被返回,继续或中断意外地绕过.

it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.

这篇关于在while循环中使用try-finally块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆