Considering this code, can I be absolutely sure that the finally
block always executes, no matter what something()
is?
try
Concisely, in the official Java Documentation (Click here), it is written that -
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Yes, finally block is always execute. Most of developer use this block the closing the database connection, resultset object, statement object and also uses into the java hibernate to rollback the transaction.
finally
will execute and that is for sure.
finally
will not execute in below cases:
case 1 :
When you are executing System.exit()
.
case 2 :
When your JVM / Thread crashes.
case 3 :
When your execution is stopped in between manually.
Example code:
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int test() {
try {
return 0;
}
finally {
System.out.println("finally trumps return.");
}
}
Output:
finally trumps return.
0
That is the whole idea of a finally block. It lets you make sure you do cleanups that might otherwise be skipped because you return, among other things, of course.
Finally gets called regardless of what happens in the try block (unless you call System.exit(int)
or the Java Virtual Machine kicks out for some other reason).
A logical way to think about this is: