The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.
When finally will not execute?
- If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.
- 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.
- If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.
From the sample code below we can notice that finally block is not executed while JVM exits in catch block.
Here you can notice, code inside finally block is not executed.
When finally will not execute?
- If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.
- 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.
- If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.
From the sample code below we can notice that finally block is not executed while JVM exits in catch block.
public static void main(String[] args)
{
try
{
System.out.println("IN TRY BLOCK");
throwsMethod();
}
catch (Exception e)
{
System.out.println("IN CATCH BLOCK");
System.exit(0);
}
finally
{
System.out.println("IN FINALLY BLOCK");
}
}
static void throwsMethod() throws Exception
{
throw new Exception("Exception thrown manually");
}
Code output:
IN TRY BLOCK
IN CATCH BLOCK
Here you can notice, code inside finally block is not executed.
No comments:
Post a Comment