This question is aimed at how the JVM is able to guarantee the execution of a finally block (provided the JVM doesn't crash and the thread is not interrupted or exited).
Prompted by an interview question, I am trying to understand how the JVM is able to ensure a finally block is executed even in strange circumstances... Consider the following code:
try{
int[] someArray = new int[10];
int invalid = someArray[10];
}
catch(IndexOutOfBoundsException e){
throw new RuntimeException("Other Exception");
}
finally{
//close open files or HTTP connections etc.
}
While this may be an odd circumstance, the finally block is still guaranteed to be executed despite the Other Exception not being explicitly handled. How does the JVM handle situations like this?
My Thoughts:
From what I understand and have read so far, when an unhandled exception is encountered, control is transferred from the current thread (to that thread's ThreadGroup
I think). Could there be some provision in the ThreadGroup
that checks for finally blocks that need executing? The only other thing I can think of is perhaps the address of the finally block is stored somewhere. Then JVM does a goto when an exception is detected and returns to the exception when the finally block has finished execution.
Can anyone clarify how this process actually happens?
See Question&Answers more detail:os