Thursday, June 13, 2013

Importance of finally block in Java

Hi All,

Welcome to Java-recent.
Today we will discuss about finally block in Java.

finally is used in accordance with try block.This block is used to clean up the resources that are created in try block

  • finally is important block in exception handling
  • the code written in finally block will be surely executed by JVM
  • The purpose of using this block is to free up the resources/de-referencing objects that got created in try block(clean-up)

Important: 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 alwaysrecovered.
If you are using Java SE 7 or later, consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed.

Note:- finally block will not get executed when we call System.exit() before execution of catch blog.

For more info refer the following post

Example :-

public class ExceptionExample {
static String empName;

public static void main(String[] args) {
try
{
System.out.println(empName.length());
}
finally
{
System.out.println("in finally block");
}
System.out.println("after exception handling");
}
}

Output:-
Exception in thread "main" in finally block
java.lang.NullPointerException
at com.javarecent.exception.ExceptionExample.main(ExceptionExample.java:22)


We can observe that code in finally is executed though exception has occured

                        Happy Learning

Please provide your valuable comments on this article and share it across your network.


No comments:

Post a Comment

Like and Share