Is there any condition where finally might not run in java? Thanks.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
In following cases, finally block will not be executed :-
System.exit(0)
is invoked fromtry
block.try
blockThere may also be other fringe cases, where finally block will not be executed.
There are two ways to stop finally block code execution:
1. Use System.exit();
2. If somehow execution control don't reach to try block.
See:
I've come across a very specific case of the finally block not executing related specifically to the play framework.
I was surprised to find that the finally block in this controller action code only got called after an Exception, but never when the call actually succeeded.
Perhaps the thread is terminated or something when renderBinary() is called. I would suspect the same thing happens for other render() calls, but I didn't verify it.
I solved the problem by moving the renderBinary() to after the try/catch. Further investigation revealed that play provides an @Finally annotation to create a method that gets executed after a controller action executes. The caveat here is that this will get called after the execution of ANY action in the controller, so it may not always be a good choice.
from the Sun Tutorials
I don't know of any other ways the finally block wouldn't execute...
Just to expand on what others have said, anything that does not cause something like the JVM exiting will incur the finally block. So the following method:
will strangely both compile and return 1.
The Sun tutorial has been wrongly quoted here in this thread.
Note: If the JVM exits while the try or catch code is being executed, then the finally block will not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block will not execute even though the application as a whole continues.
If you look into sun tutorial closely for finally block, it doesn't say "will not execute" but "may not execute" Here is the correct description
The apparent reason for this behavior is, call to system.exit() is processed in a runtime system thread which may take time to shutdown the jvm, meanwhile thread scheduler can ask finally to execute. So finally is designed to always execute, but if you are shutting down jvm, it may happen that jvm shuts down prior to finally getting being executed.