Using try-finally block inside while loop [duplicate]
Asked Answered
S

2

7

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
Sheaff answered 8/2, 2018 at 9:31 Comment(0)
V
5

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.

Violone answered 8/2, 2018 at 9:33 Comment(0)
B
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.

Boisterous answered 8/2, 2018 at 9:35 Comment(2)
There are rare exceptions - System.exit(n) avoids the finally.Lidalidah
@Lidalidah Thanks, didn't know that.Boisterous

© 2022 - 2024 — McMap. All rights reserved.