Sunday 5 August 2012

What is finally block in java?

The Finally block in java is used along with the try-catch statements. The usual structure is 

try {
 .....
} catch (Exception e) {
 ....
} finally {
 .....
}

 When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is thrown. See the example given below,


public class MyFinallyBlock {
public static void main(String[] a) {
/**
* Exception will occur here, after catch block  the contol will goto
* finally block.
**/
try {
int i = 10 / 0;
} catch (Exception ex) {
System.out.println("Inside 1st catch Block");
} finally {
System.out.println("Inside 1st finally block");
}
/**
* In this case exception won't, after executing try block  the contol
* will goto finally block.
**/
try {
int i = 10 / 10;
} catch (Exception ex) {
System.out.println("Inside 2nd catch Block");
} finally {
System.out.println("Inside 2nd finally block");
}
}
}

 The output is:


Inside 1st catch Block
Inside 1st finally block
Inside 2nd finally block


The run-time system always executes the code within the finally block regardless of what happens in the try block. So it is the ideal place to keep cleanup code such as closing the files and releasing system resources .This ensures that the finally block is executed even if an unexpected exception occurs.

Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated Let us take one example:



void writeFile() {
PrintWriter out = null;
try {
FileWriter fr = new FileWriter("C:\t1.txt");
out = new PrintWriter(fr);
out.println("finally block example");
} catch (IOException e) {
System.out.println(e);
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}


The try block of the writeFile method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeFile method. This poses a somewhat complicated problem because writeFile's try block can exit in one of two ways.

  •  The new FileWriter statement fails and throws an IOException.
  •  Everything succeeds and the try block exits normally. 

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 for the writeFile method cleans up and then closes the PrintWriter.

In the writeFile example, you could provide for cleanup without the intervention of a finally block. For example, you could put the code to close the PrintWriter at the end of the try block and again within each exception handlers as follows.

try { // Don't do this; it duplicates code.
out.close();

} catch (FileNotFoundException e) {
// Don't do this; it duplicates code.
out.close();
System.err.println("Caught FileNotFoundException: "
+ e.getMessage());
} catch (IOException e) {
// Don't do this; it duplicates code.
out.close();
System.err.println("Caught IOException: " + e.getMessage());
}

However, this duplicates code, thus making the code difficult to read and error-prone should you modify it later. For example, if you add code that can throw a new type of exception to the try block, you have to remember to close the PrintWriter within the new exception handler.

 Is the “finally” block guaranteed to be called ?


 If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, 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.

See the example given below.Here there is no guarantee that the finally block will be executed or not.

public class Main {

public static void main(String args[]) {
try {
System.out.println("try");
System.exit(0);
} catch (Exception e) {
System.out.println("exception");
} finally {
System.out.println("finally");
}
}
}

What if an exception occurs in the finally block?


 An issue for which there's no really neat solution is that code in the finally block could itself throw an exception.In this case, the exception in the finally block would be thrown instead of any exception occurring inside the try block. Since code in the finally block is intended to be "cleanup" code, we could decide to treat exceptions occurring there as secondary, and to put an explicit catch: 

public int readNumber(File f) throws IOException, NumberFormatException {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(f), "ASCII"));
try {
return Integer.parseInt(br.readLine());
} finally {
try {
br.close();
} catch (IOException e) { // possibly log e } } }
}
}
}

Conclusion:


 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 always recovered.

 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.

No comments:

Post a Comment