Does a finally block always get executed in Java?
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
try
orcatch
block - 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
finally
block is going to be executed by a daemon thread and all other non-daemon threads exit beforefinally
is called
Does a finally block always get executed in Java?
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
try
orcatch
block - 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
finally
block is going to be executed by a daemon thread and all other non-daemon threads exit beforefinally
is called
Does a finally block always run?
from the Sun Tutorials
Note: 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.
I don't know of any other ways the finally block wouldn't execute...
Is there possibility that a finally block might not execute?
If the JVM exits while the
try
orcatch
code is being executed, then thefinally
block may not execute. Likewise, if the thread executing thetry
orcatch
code is interrupted or killed, thefinally
block may not execute even though the application as a whole continues.
Source: java.sun.com: Java Tutorial: The finally Block
Does a finally block run even if you throw a new Exception?
Yes, the finally blocks always runs... except when:
- The thread running the try-catch-finally block is killed or interrupted
- You use
System.exit(0);
- The underlying VM is destroyed in some other way
- The underlying hardware is unusable in some way
Additionally, if a method in your finally block throws an uncaught exception, then nothing after that will be executed (i.e. the exception will be thrown as it would in any other code). A very common case where this happens is java.sql.Connection.close()
.
As an aside, I am guessing that the code sample you have used is merely an example, but be careful of putting actual logic inside a finally block. The finally block is intended for resource clean-up (closing DB connections, releasing file handles etc), not for must-run logic. If it must-run do it before the try-catch block, away from something that could throw an exception, as your intention is almost certainly functionally the same.
When finally is executed?
The finally block always executes when the try block exits
(click).
when does the finally block not execute while try or catch block is interrupted
Good answers can be found here.
Besides a System.exit()
, the finally block will not run if the JVM crashes for some reason (e.g. infinite loop in your try
block).
As far as the thread itself, only if it is stopped using the stop()
method (or suspend()
without resume()
) will the finally
block not be executed. A call to interrupt()
will still result in the finally
block being executed.
It's also worth noting that, since any return
statement in the finally
block will override any returns or exception throws in the try
/catch
blocks, program behavior can quickly become erratic and hard to debug if this happens to you. Not really anything worth taking precaution against (as it only happens in extremely rare cases), but worth being aware of so you can recognize it when it happens.
why is the statement in finally block executed despite using return in try block
Because that's what it's designed to do. It is not like catch (...)
in C++ (which only executes if not caught elsewhere).
finally
can be very useful in cleaning up resources: it is one way that Java introduces RAII-type features that are more prevalent in other languages like C++ (via destructors). Java more naturally performs clean-up via the garbage collector but finally
permits an alternative approach.
Does the finally block execute if the thread running the function is interrupted?
According to the Java Tutorials, "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."
Here's the full passage:
The
finally
block always executes when thetry
block exits. This
ensures that thefinally
block is executed even if an unexpected
exception occurs. Butfinally
is useful for more than just exception
handling — it allows the programmer to avoid having cleanup code
accidentally bypassed by areturn
,continue
, orbreak
. Putting cleanup
code in afinally
block is always a good practice, even when no
exceptions are anticipated.Note: If the JVM exits while the
try
orcatch
code is being executed, then
thefinally
block may not execute. Likewise, if the thread executing
thetry
orcatch
code is interrupted or killed, thefinally
block may
not execute even though the application as a whole continues.
class Thread1 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("finally executed");
}
}
}
...
t1.start();
t1.interrupt();
It prints - finally executed
Related Topics
How Do Servlets Work? Instantiation, Sessions, Shared Variables and Multithreading
Why Does My Arraylist Contain N Copies of the Last Item Added to the List
Why Don't Java'S +=, -=, *=, /= Compound Assignment Operators Require Casting
Why Do I Need to Override the Equals and Hashcode Methods in Java
How to Append Text to an Existing File in Java
How to Generate a Random Alpha-Numeric String
Variable Might Not Have Been Initialized Error
Java 256-Bit Aes Password-Based Encryption
Java Generics Type Erasure: When and What Happens
How to Create a File and Write to It
How to Import the Javax.Servlet/Jakarta.Servlet API in My Eclipse Project
How to Read/Convert an Inputstream into a String in Java
How to Determine Whether an Array Contains a Particular Value in Java
Java.Util.Nosuchelementexception - Scanner Reading User Input
Android/Java - Date Difference in Days
Technically What Is the Main Difference Between Oracle Jdk and Openjdk
Gson Throwing "Expected Begin_Object But Was Begin_Array"
How to Upload a File Using Java Httpclient Library Working With PHP