Using a try-finally block inside a while loop

I am trying to understand the mechanism when I finally use inside the while loop. In the code below. A line is printed at the end , and during breaks. I expected the code to not reach the finally block. Or, if it reaches the finally block, there is no gap , so time should go on. 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

 in while in finally after while 
+5
source share
2 answers

Despite the fact that you break guaranteed that it will always be executed at runtime. You cannot permanently enter the control.

https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

The finally block is always executed when the try block completes. This ensures that the finally block is executed even if an unexpected exception occurs. But, finally, it is useful not only for exception handling - this allows the programmer to avoid accidentally bypassing the cleanup code by returning, continuing, or breaking.

There is a reason for the behavior. It helps us.

it allows the programmer to avoid accidentally bypassing the cleanup code by returning, continuing, or breaking.

+3
source

In short, no matter what you do inside try , to finally exit the current loop or function, finally is executed. This is true for any return , break , continue and just about everything else that takes you anywhere: try can (usually) remain only through finally .

However, there are exceptions: as OldCurmudgeon notes, System.exit () does - if successful - does not execute finally .

0
source

Source: https://habr.com/ru/post/1275237/


All Articles