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...
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
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.
Does the C# finally block ALWAYS execute?
yes it does :-) http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
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.
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 'finally' always execute in Python?
"Guaranteed" is a much stronger word than any implementation of finally
deserves. What is guaranteed is that if execution flows out of the whole try
-finally
construct, it will pass through the finally
to do so. What is not guaranteed is that execution will flow out of the try
-finally
.
A
finally
in a generator or async coroutine might never run, if the object never executes to conclusion. There are a lot of ways that could happen; here's one:def gen(text):
try:
for line in text:
try:
yield int(line)
except:
# Ignore blank lines - but catch too much!
pass
finally:
print('Doing important cleanup')
text = ['1', '', '2', '', '3']
if any(n > 1 for n in gen(text)):
print('Found a number')
print('Oops, no cleanup.')Note that this example is a bit tricky: when the generator is garbage collected, Python attempts to run the
finally
block by throwing in aGeneratorExit
exception, but here we catch that exception and thenyield
again, at which point Python prints a warning ("generator ignored GeneratorExit") and gives up. See PEP 342 (Coroutines via Enhanced Generators) for details.Other ways a generator or coroutine might not execute to conclusion include if the object is just never GC'ed (yes, that's possible, even in CPython), or if an
async with
await
s in__aexit__
, or if the objectawait
s oryield
s in afinally
block. This list is not intended to be exhaustive.A
finally
in a daemon thread might never execute if all non-daemon threads exit first.os._exit
will halt the process immediately without executingfinally
blocks.os.fork
may causefinally
blocks to execute twice. As well as just the normal problems you'd expect from things happening twice, this could cause concurrent access conflicts (crashes, stalls, ...) if access to shared resources is not correctly synchronized.Since
multiprocessing
uses fork-without-exec to create worker processes when using the fork start method (the default on Unix), and then callsos._exit
in the worker once the worker's job is done,finally
andmultiprocessing
interaction can be problematic (example).- A C-level segmentation fault will prevent
finally
blocks from running. kill -SIGKILL
will preventfinally
blocks from running.SIGTERM
andSIGHUP
will also preventfinally
blocks from running unless you install a handler to control the shutdown yourself; by default, Python does not handleSIGTERM
orSIGHUP
.- An exception in
finally
can prevent cleanup from completing. One particularly noteworthy case is if the user hits control-C just as we're starting to execute thefinally
block. Python will raise aKeyboardInterrupt
and skip every line of thefinally
block's contents. (KeyboardInterrupt
-safe code is very hard to write). - If the computer loses power, or if it hibernates and doesn't wake up,
finally
blocks won't run.
The finally
block is not a transaction system; it doesn't provide atomicity guarantees or anything of the sort. Some of these examples might seem obvious, but it's easy to forget such things can happen and rely on finally
for too much.
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
When does a finally block execute if the catch block contains a continue statement?
Think of it as a try/finally block with catch expressions optional. Both continue statements in your code would pop the execution stack out of the catch which would place execution in the finally block before allowing the loop to continue. Any time there is a try/finally block, finally will always be executed.
Related Topics
How to Populate a Listview in Javafx Using Custom Objects
Reliable File.Renameto() Alternative on Windows
Accessing a Variable from Another Class
Can Java Call Parent Overridden Method in Other Objects But Not Subtype
How to Do Arithmetic Operations on the Number Baseclass
Java: Reading a File into an Array
Determine Which Jar File a Class Is From
How to Create Table Using Ascii in a Console
How to Sort an Array of Ints Using a Custom Comparator
How to Replace Case-Insensitive Literal Substrings in Java
Java MVC - How to Divide a Done Text Game into MVC
How to Show/Hide a Column at Runtime
Jvm Takes a Long Time to Resolve Ip-Address for Localhost
How to Create Custom Methods for Use in Spring Security Expression Language Annotations
Spring Aop Not Working for Method Call Inside Another Method
Creation Timestamp and Last Update Timestamp with Hibernate and MySQL