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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With