I never properly understood the use of the finally statement. Can anyone tell me what the difference is between:
try { a; block; off; statements; } catch (Exception e) { handle; exception; e; } finally { do; some; cleanup; }
on the one hand and:
try { a; block; off; statements; } catch (Exception e) { handle; exception; e; } do; some; cleanup;
On the other
We generally use the finally block to execute clean up code like closing connections, closing files, or freeing up threads, as it executes regardless of an exception. Note: try-with-resources can also be used to close resources instead of a finally block.
The finally keyword is used as a block to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.
They differ if
try
-block completes by throwing a java.lang.Throwable
that is not a java.lang.Exception
, for instance because it is a java.lang.Error
such as AssertionError
or OutOfMemoryError
.continue
, break
or return
More generally, the java language guarantees that a finally block is executed before the try-statement completes. (Note that if the try-statement does not complete, there is no guarantee about the finally. A statement might not complete for a variety of reasons, including hardware shutdown, OS shutdown, VM shutdown (for instance due to System.exit
), the thread waiting (Thread.suspend()
, synchronized
, Object.wait()
, Thread.sleep()
) or being otherwise busy (endless loops, ,,,).
So, a finally
block is a better place for clean-up actions than the end of the method body, but in itself, still can not guarantee cleanup exeuction.
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