Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. In java we use the try and catch blocks for exception handling mechanism. try defines the block of code in which exceptions may occur. One or more catch clauses match a specific exception (or group of exceptions—more on that later) to a block of code that handles it.
Although try and catch provide mechanism for trapping and handling exceptions, yet there is a problem of if we have allocated a network socket or opened a file somewhere in the guarded region (try block), then where to perform any cleanup that our code requires.
Why do not we place our cleanup code in try or in catch block?
We know that Finally block is the right place to close your files, release our network sockets, and perform any other cleanup that our code requires. Then we may think why do not we keep the cleanup code in try or catch block and why having this overhead of writing finally block for cleaning up.
Let us see why is it so:
Placing the cleanup code in try block is bad idea because it does not guarantee us that the cleanup code will get executed. This is because execution transfers out of the try block as soon as an exception is thrown and therefore we can't put our cleanup code at the bottom of the try block and expect it to be executed if an exception occurs.
Now the question arises that why are catch blocks poor place for placing our clean up codes?
If we want to write our cleanup code in catch block then each handler requires its own copy of the cleanup code , i.e. each exception handler would have to close the file or release the socket. By doing so we enhance a lot of redundant code, an also there are chances that we may forget to do cleanup.
And therefore Java offers the finally block. A finally block runs in every situation , even if there is a return statement in the try block. If an exception is not thrown, finally runs. If the exception is caught, finally runs. If the exception is not caught, finally runs.
When does finally block not get executed?
The official website of sun java tutorial has mentioned:
“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.”
Technically, there are two conditions where by finally block will not get executed in Java and they are system.exit(0) and logic in try block is into infinite loop. Both of them will cause JVM to end.