View RSS Feed

My Java Tips

Finally Block

Rate this Entry
by , 10-25-2011 at 08:17 PM (598 Views)
You must be using try catch block in your programming practices. The finally block is used to ensure resources are recovered regardless of any problems that may occur.


Remember that there are several different ways of using the finally block and it depends on how exceptions are handled. Let me introduce the first style. If a method throws all exceptions, then it may use a finally with no catch :

Java Code:
import java.io.*;
 

public final class SimpleFinally {
public static void main(String... aArgs) throws IOException {

  simpleFinally("C:\Temp\test.txt");

  }

private static void simpleFinally(String aFileName) throws IOException {

  //If this line throws an exception, then the finally block will NOT execute.
  //That is a good thing, since reader will be null.
  BufferedReader reader = new BufferedReader(new FileReader(aFileName));

  try {

  //Any exception in the try block will cause the finally block to execute

  String line = null;

  while ( (line = reader.readLine()) != null ) {
  //process the line...
  }
  }

  finally {

  //No check for null is required here
  reader.close();

  }
  }
}
I'll now present a different approach for finally block.


Lets assume that a method handles all exceptions. We can nest a try..finally within a try..catch. This is useful when the finally block throws the same exceptions as the rest of the code. This style may seem slightly complex, it appears to be superior to alternative styles :

Java Code:
import java.io.*;
import java.util.logging.*;

public final class NestedFinally {

  public static void main(String... aArgs) {
    nestedFinally("C:\Temp\test.txt");
  }

  private static void nestedFinally(String aFileName) {
    try {
      //If the constructor throws an exception, the finally block will NOT execute
      BufferedReader reader = new BufferedReader(new FileReader(aFileName));
      try {
        String line = null;
        while ( (line = reader.readLine()) != null ) {
          //process the line...
        }
      }
      finally {
        //no need to check for null
        //any exceptions thrown here will be caught by
        //the outer catch block
        reader.close();
      }
    }
    catch(IOException ex){
      fLogger.severe("Problem occured : " + ex.getMessage());
    }
  }

  private static final Logger fLogger =
    Logger.getLogger(NestedFinally.class.getPackage().getName());
}
This post will present more verbose style places a catch within the finally. This style is likely the least desirable, since it has the most blocks.


Java Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Logger;

public final class CatchInsideFinally {

  public static void main(String... aArgs) {
    catchInsideFinally("C:\Temp\test.txt");
  }

  private static void catchInsideFinally(String aFileName) {
    //Declared here to be visible from finally block
    BufferedReader reader = null;
    try {
      //if this line fails, finally will be executed, and reader will be null
      reader = new BufferedReader(new FileReader(aFileName));
      String line = null;
      while ( (line = reader.readLine()) != null ) {
        //process the line...
      }
    }
    catch(IOException ex){
      fLogger.severe("Problem occured : " + ex.getMessage());
    }
    finally {
      try {
        //need to check for null
        if ( reader != null ) {
          reader.close();
        }
      }
      catch(IOException ex){
        fLogger.severe("Problem occured. Cannot close reader : " + ex.getMessage());
      }
    }
  }

  private static final Logger fLogger =
    Logger.getLogger(CatchInsideFinally.class.getPackage().getName());
}

Submit "Finally Block" to Facebook Submit "Finally Block" to Digg Submit "Finally Block" to del.icio.us Submit "Finally Block" to StumbleUpon Submit "Finally Block" to Google

Updated 10-25-2011 at 08:36 PM by Java Tip

Tags: None Add / Edit Tags
Categories
Java SE

Comments