Earlier we discussed about NullPointerException and this tutorial is also on exception handling in Java. It is essential to have an understanding of exception handling before we start a discussion on finally blocks. Following is a brief introduction to exception handling in Java.

Exception handling

Exception handling is a way to handle erroneous situations using code. In a large program with too many execution paths and inputs, it is very difficult to capture all use case scenario. If an error occurs in application which has not been taken care of, the application will pass the Exception to JVM which will eventually result in shutting down of the JVM.

try and catch

To handle this scenario, we have try and catch blocks which can help the program to recover from error and display some meaningful error message to the user. The following program showcases exception handling:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test {

	public static void main(String[] args) {
		File logFile = new File("c:\\test.log");
		FileReader fr = null;
		try {
			fr = new FileReader(logFile);
			System.out.println(fr.read());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
                        //Display proper message and recover from exception
		} catch (IOException e) {
			e.printStackTrace();
                        //Display proper message and recover from exception
		}
	}
}

Always release resources

Usually programs initialize resources for performing their task and make use them before finally releasing the resources. In our above example, we have initialize a file handler in Java for reading the log file.

Ideally, we should be reading text from this file and then disposing of the FileReader and File objects so that the file pointers are released from the memory. The modified code which releases the file handlers is shown below:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test {

	public static void main(String[] args) {
		File logFile = new File("c:\\test.log");
		FileReader fr = null;
		try {
			fr = new FileReader(logFile);
			System.out.println(fr.read());
			fr.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
                        //Display proper message and recover from exception
		} catch (IOException e) {
			e.printStackTrace();
                        //Display proper message and recover from exception
		}
		logFile = null;
	}
}

There is still an issue with the above program that if there is an issue while reading from the file, an IOException shall be raised and the program will quit. In case of an application with multiple modules, we shall want the application to be running in-spite of the exception which is done by our exception handling catch block.

The finally block

But what about the file handlers in case of exceptions in the application, will they be released? No, in our above version of the program, fr.close() statement will not be executed when an exception occurs during fr.read(). The solution of this problem is to use finally block. Here is the definition of finally block for your ready reference:

finally block is used to add any code which should be executed irrespective of whether an exception is raised from a try/catch block or not.

Thus any code which you are dead sure that it should be executed in any scenario, add it in the finally block. Our last version of code is updated here with finally block:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test {

	public static void main(String[] args) {
		File logFile = new File("c:\\test.log");
		FileReader fr = null;
		try {
			fr = new FileReader(logFile);
			System.out.println(fr.read());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
                        //Display proper message and recover from exception
		} catch (IOException e) {
			e.printStackTrace();
                        //Display proper message and recover from exception
		} finally {
			try {
				if(fr!=null) {
					fr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
                                //Display proper message and recover from exception
			}			
		}
		logFile = null;
	}
}

Bonus Tip: We can avoid the use of try/catch/finally by using the try with resources block of JDK 1.7 which ultimately expands to the above version.

De-compiled code for finally block

The de-compiled version of the above code is reproduced here from reference:

import java.io.*;

public class Test
{

    public Test()
    {
    }

    public static void main(String args[])
    {
        File logFile;
        FileReader fr;
        logFile = new File("c:\\test.log");
        fr = null;
        fr = new FileReader(logFile);
        System.out.println(fr.read());
        break MISSING_BLOCK_LABEL_109;
        FileNotFoundException e;
        e;
        e.printStackTrace();
        try
        {
            if(fr != null)
            {
                fr.close();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        break MISSING_BLOCK_LABEL_127;
        e;
        e.printStackTrace();
        try
        {
            if(fr != null)
            {
                fr.close();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        break MISSING_BLOCK_LABEL_127;
        Exception exception;
        exception;
        try
        {
            if(fr != null)
            {
                fr.close();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        throw exception;
        try
        {
            if(fr != null)
            {
                fr.close();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        logFile = null;
        return;
    }
}

As we can see, whole lot of extra code has been added by the Java compiler as a replacement of finally block. If we use the try with resources block of JDK 1.7, we shall get similar code but without the unnecessary repetitive try/catch block in the finally block.

Related Posts

finally executes finally admin Core Java
Earlier we discussed about NullPointerException and this tutorial is also on exception handling in Java. It is essential to have an understanding of exception handling before we start a discussion on finally blocks. Following is a brief introduction to exception handling in Java. Exception handling Exception handling is a way to...
<p>Earlier we discussed about <a href="http://www.javaexperience.com/java-null-value-and-nullpointerexception/">NullPointerException</a> and this tutorial is also on exception handling in Java. It is essential to have an understanding of exception handling before we start a discussion on finally blocks. Following is a brief introduction to exception handling in Java.</p> <h2>Exception handling</h2> <p>Exception handling is a way to handle erroneous situations using code. In a large program with too many execution paths and inputs, it is very difficult to capture all use case scenario. If an error occurs in application which has not been taken care of, the application will pass the Exception to JVM which will eventually result in shutting down of the JVM.</p> <h2>try and catch</h2> <p>To handle this scenario, we have try and catch blocks which can help the program to recover from error and display some meaningful error message to the user. The following program showcases exception handling:</p> 1 <h2>Always release resources</h2> <p>Usually programs initialize resources for performing their task and make use them before finally releasing the resources. In our above example, we have initialize a file handler in Java for reading the log file. Ideally, we should be reading text from this file and then disposing of the FileReader and File objects so that the file pointers are released from the memory. The modified code which releases the file handlers is shown below:</p> 1 <p>There is still an issue with the above program that if there is an issue while reading from the file, an IOException shall be raised and the program will quit. In case of an application with multiple modules, we shall want the application to be running in-spite of the exception which is done by our exception handling catch block. </p> <h2>The finally block</h2> <p>But what about the file handlers in case of exceptions in the application, will they be released? No, in our above version of the program, fr.close() statement will not be executed when an exception occurs during fr.read(). The solution of this problem is to use finally block. Here is the definition of finally block for your ready reference: <blockquote>finally block is used to add any code which should be executed irrespective of whether an exception is raised from a try/catch block or not.</blockquote> </p> <p>Thus any code which you are dead sure that it should be executed in any scenario, add it in the finally block. Our last version of code is updated here with finally block:</p> 1 <p><strong>Bonus Tip:</strong> We can avoid the use of try/catch/finally by using the try with resources block of JDK 1.7 which ultimately expands to the above version.</p> <h2>De-compiled code for finally block</h2> The de-compiled version of the above code is reproduced here from reference: 1 <p>As we can see, whole lot of extra code has been added by the Java compiler as a replacement of finally block. If we use the try with resources block of JDK 1.7, we shall get similar code but without the unnecessary repetitive try/catch block in the finally block.</p>
How to detect browser proxy using Java program
What is Double Brace Initialization in Java
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Latest posts by admin (see all)

Comments

comments