Why use finally
Solution 1:
They differ if
- the
try
-block completes by throwing ajava.lang.Throwable
that is not ajava.lang.Exception
, for instance because it is ajava.lang.Error
such asAssertionError
orOutOfMemoryError
. - the try-block completes abruptly using a control flow statement such a
continue
,break
orreturn
- the catch-block completes abruptly (by throwing any throwable, or using a control flow statement)
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.
Solution 2:
finally
block executes always.
finally
block is used for cleanup, like to free resources used within try
/catch
, close db connections, close sockets, etc.. even when an unhandled exception occurs within your try
/catch
block.
The only time the finally
block doesn't execute is whensystem.exit()
is called in try
/catch
or some error occurs instead of an exception.
The error in the description above means when Java application exit with conditions like Out Of Memory error. I see some downvotes :( for this reason it seems.