-->

Using try-finally block inside while loop [duplica

2019-06-23 07:43发布

问题:

This question already has an answer here:

  • Does a finally block always get executed in Java? 46 answers

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.