Friday, 22 May 2015

finally block in Java exception handling

When an exception occurs in the code, the flow of the execution may change or even end abruptly. That may cause problem if some resources were opened in the method where exception occurred.

As example - In a method a file was opened, while executing code in the method some exception occurred so the opened file was never closed, which effectively means that the resources will remain open consuming memory.

You do need some mechanism to handle such scenarios. That's where finally block helps by providing exception-handling mechanism to clean up.

Code with in the finally block will be executed after try/catch block has completed. Also note that the finally block will always be executed whether or not an exception is thrown.

If the code with in try block executes without throwing any exception, the finally block is executed immediately after the completion of try block. If an exception is thrown with in the try block, the finally block is executed immediately after executing the catch block (if exists) which handled the thrown exception.

Example of finally

Note that, even if there is a return statement in try block, finally will be executed.

public class FinallyDemo {

 public static void main(String[] args) {
  int i = displayValue();
  System.out.println("Value of i " + i);

 }
 
 static int displayValue(){
  try{
   System.out.println("In try block");
   return 1;
  }finally{
   System.out.println("In finally block");
   return 2;
  }
 }

}

Output

In try block
In finally block
Value of i 2

It can be seen, though try block has a return value and no exception is thrown, still finally is executed. Ultimately return value is what finally returns.

Even if the exception is thrown still return value will be what finally returns. Let's see the same example again, this time an exception will be thrown.

public class FinallyDemo {

 public static void main(String[] args) {
  int i = displayValue();
  System.out.println("Value of i " + i);

 }
 
 static int displayValue(){
  try{
   System.out.println("In try block");
   throw new NullPointerException();
  }catch(NullPointerException nExp){
   System.out.println("Exception caught in catch block of displayValue");
   return 2;
  }finally{
   System.out.println("In finally block");
   //return 3;
  }
 }

}

Output

In try block
Exception caught in catch block of displayValue
In finally block
Value of i 3

Please note that it is not a good idea to return any thing from finally as it will suppress the exception. finally must be used for cleaning up.

Points to note -

  • Every try block must be followed by at least one catch or a finally clause. So we can have any of these combinations try-catch, try-finally or try-catch-finally blocks.
  • When method is about to return from its try-catch block after normal execution flow or because of an uncaught exception, finally block is executed just before the method returns.
  • If there are multiple catch blocks and none of them can handle the exception thrown, even then the finally bock is executed.
  • Though there can be multiple catch blocks associated with a single try statement but there can only be single finally block associated with a try block. In case of nested try blocks there can be associated finally blocks with respective try blocks.
  • Finally block is used to close the allocated resources (like file handles, database connections) before returning from the method.
  • It's not a good idea to return any value from finally as it may cause any exceptions that are not caught in the method to be lost.
  • If the JVM exits (through System.exit() or JVM crash) while the try or catch code is being executed, then the finally block may not execute. In case of multithreading 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.

That's all for this topic finally block in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. final Vs finally Vs finalize
  2. How to create a custom exception class
  3. Nested try statements
  4. finalize method in Java
  5. Lambda expression and exception handling
  6. Java Exception Handling interview questions

You may also like -

1 comment:

  1. Can a finally block contain any code which rises an exception?(May not be the purpose of finally)

    ReplyDelete