try, catch, finally in java

finally block will be executed whenever try and/or catch ends or return happens in try and/or catch. A try block must be matched by at least one of catch and finally, or both.

finally can ensure proper cleanup are conducted. Without finally, consider the return, continue, or break happens before the cleanup code in catch get executed, or there is no catch with the matched exception type that is thrown by try.  In both cases, cleanup code will be passed by and resources is not declaimed. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

But exception thrown in finally will still face the problem faced by a try block without catch. So when exception might be thrown in a code in Finally, we should add try and catch within finally.

However:  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.

( see


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s