They differ if
- the
try-block completes by throwing ajava.lang.Throwablethat is not ajava.lang.Exception, for instance because it is ajava.lang.Errorsuch asAssertionErrororOutOfMemoryError. - the try-block completes abruptly using a control flow statement such a
continue,breakorreturn - 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.
Videos
They differ if
- the
try-block completes by throwing ajava.lang.Throwablethat is not ajava.lang.Exception, for instance because it is ajava.lang.Errorsuch asAssertionErrororOutOfMemoryError. - the try-block completes abruptly using a control flow statement such a
continue,breakorreturn - 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.
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.
Yes, finally will be called after the execution of the try or catch code blocks.
The only times finally won't be called are:
- If you invoke
System.exit() - If you invoke
Runtime.getRuntime().halt(exitStatus) - If the JVM crashes first
- If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the
tryorcatchblock - If the OS forcibly terminates the JVM process; e.g.,
kill -9 <pid>on UNIX - If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
- If the
finallyblock is going to be executed by a daemon thread and all other non-daemon threads exit beforefinallyis called
Example code:
public class Test {
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int test() {
try {
return 0;
}
finally {
System.out.println("something is printed");
}
}
}
Output:
something is printed
0
Maybe I’m just too early in learning Java to understand the reason you’d use it and for my purposes it’s irrelevant, but I’m curious.
I know it executes regardless of whether an exception is caught but doesn’t the code below a try {} catch {} block also execute regardless of whether an exception is caught? Isn’t that PART of the point of catching the exception? For the code to continue?
Forgive my ignorance, as there may be some serious misunderstandings of concepts in this post.
Thank you.
These are two different things:
- The catch block is only executed if an exception is thrown in the try block.
- The finally block is executed always after the try(-catch) block, if an exception is thrown or not.
In your example you haven't shown the third possible construct:
try {
// try to execute this statements...
}
catch( SpecificException e ) {
// if a specific exception was thrown, handle it here
}
// ... more catches for specific exceptions can come here
catch( Exception e ) {
// if a more general exception was thrown, handle it here
}
finally {
// here you can clean things up afterwards
}
And, like @codeca says in his comment, there is no way to access the exception inside the finally block, because the finally block is executed even if there is no exception.
Of course you could declare a variable that holds the exception outside of your block and assign a value inside the catch block. Afterwards you can access this variable inside your finally block.
Throwable throwable = null;
try {
// do some stuff
}
catch( Throwable e ) {
throwable = e;
}
finally {
if( throwable != null ) {
// handle it
}
}
These are not variations, they're fundamentally different things. finally is executed always, catch only when an exception occurs.