Using try-finally block inside while loop [duplicate]

ぐ巨炮叔叔 提交于 2019-12-10 13:47:58

问题


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");

Output is

in while
in finally
after while

回答1:


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

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.




回答2:


In short, whatever you do inside try to exit the current loop or function, finally gets executed. This is true for any return, break, continue and almost everything else which would lead you anywhere: try can (usually) only be left through finally.

There are exceptions, however: as OldCurmudgeon notes, System.exit() does – ind the case of success – not make finally be executed.



来源:https://stackoverflow.com/questions/48681988/using-try-finally-block-inside-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!