Using finally block in java


Using finally with exception

                The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Finally bloack helps you to write any clean up codes, avoiding resource leakage (closing the resource used in try block, ex: jdbc connection, closing a file etc)

Finally allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

So catch is optional when using finally with catch

Syntax

try
{
			
}
catch(Exception e)
{

}
finally
{

}

 Or

try
{
			
} // catch is optional
finally
{

}

Jdk 1.5 released a new feature to release a resource using Closeable Interface

Jdk 1.7 releases a new feature to with enhanced exception handing feature AutoCloseable super type for Closeable Interface.





Comments


©candidjava.com