Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using try-finally block inside while loop [duplicate]

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
like image 579
rematnarab Avatar asked Feb 08 '18 09:02

rematnarab


2 Answers

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.

like image 74
Suresh Atta Avatar answered Sep 29 '22 11:09

Suresh Atta


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.

like image 37
glglgl Avatar answered Sep 29 '22 11:09

glglgl