In a Java try{} ... catch{} ... finally{}
block, code within the finally{}
is generally considered \"guaranteed\" to run regardless of what occurs
You can make it a part of Daemon Thread. You may use the method setDaemon(boolean status)
which is used to mark the current thread as daemon thread or user thread and exit the JVM as and when required. This will enable you exit the JVM before finally{}
is executed.
I think when JVM exits suddenly due to any reason, that can be a cause the control will not enter into the the finally block and never execute.
There is a chance of partial execution when finally itself throws an exception (or leads to an error)
Another possible instance of a finally block never executing would be due to a design where the method returned before the try block was entered, as in the cases of some very bad code I've seen from time to time:
public ObjectOfSomeType getMeAnObjectOfSomeType() throws SomeHorrendousException {
if (checkSomeObjectState()) {
return new ObjectOfSomeType();
}
try {
// yada yada yada...
} catch (SomeHorrendousException shexc) {
// wow, do something about this horrendous exception...
} finally {
// do some really important cleanup and state invalidation stuff...
}
I know none of you would ever do this, so I hesitated to add this as a possible scenario, but thought, eh, it's Friday, what the heck ; )
One could be "A finally is a part of daeomon thread it may not be executed".
Testing the finally block in different statement in try block.
public static void main(String [] args){
try{
System.out.println("Before Statement");
/*** Statement ***/
System.out.println("After Statement");
}
catch(Exception e){
}
finally{
System.out.println("Finally is Executed");
}
Statements in which finally block is executed are following:
Thread.currentThread().interrupted();
Thread.currentThread().destroy();
Thread.currentThread().stop();
Thread.sleep(10);
Thread.currentThread().interrupt();
Runtime.getRuntime().addShutdownHook(Thread.currentThread());
Statements in which finally block is not executed are following:
Thread.currentThread().suspend();
System.exit(0);
Runtime.getRuntime().exit(0);
Runtime.getRuntime().halt(0);