Wednesday, May 25, 2022

finally Block in Java Exception Handling

In the post try-catch Block in Java we have already seen how to use try catch block for exception handling. In this post we'll get to know about finally block in Java which is used along with try catch block.

finally block in Java

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.

For 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. Let's try to understand it with the following code.

1   public static void main(String[] args) {
2     BufferedReader br = null;
3     try{
4      String strLine;
5      // Instance of FileReader wrapped in a BufferedReader
6      br = new BufferedReader(new java.io.FileReader("F:\\abc.txt"));
7      ...
8      ...
9      ... //Exception happens here
10     ...
11     br.close()
12    }catch(IOException ioExp){
13     System.out.println("Error while reading file " + ioExp.getMessage());
14    }
15  }

At line 6 a BufferedReader stream is opened, which is closed in line 11. Suppose exception occurs at line 9 which changes the flow of the code execution because now the execution moves to catch block directly. Because of the exception, code execution moves from line 9 directly to line 13, meaning line 11 where stream is closed never getting executed.

You do need some mechanism to handle such scenarios. That's where finally block in Java 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 in Java is always 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 in Java

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.

Finally block Java example for cleaning up

A very good scenario when you should use finally block is when you are reading a file in Java. It is always advisable to close input and output streams in finally block in such cases to avoid resource kept opened in case of any exception.

public class FileRead {

 public static void main(String[] args) {
  BufferedReader br = null;
  try{
   String strLine;
   // Instance of FileReader wrapped in a BufferedReader
   br = new BufferedReader(new java.io.FileReader("F:\\abc.txt"));
   ...
   ...
  }catch(IOException ioExp){
   System.out.println("Error while reading file " + ioExp.getMessage());
  }finally {
   try {
    // Close the stream
    if(br != null){
     br.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

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 in Java 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 in Java
  2. Creating Custom Exception Class in Java
  3. throws Keyword in Java Exception Handling
  4. Exception Handling in Java Lambda Expressions
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. What Are JVM, JRE And JDK in Java
  2. Java Automatic Numeric Type Promotion
  3. Interface Static Methods in Java
  4. Creating a Thread in Java
  5. Synchronization in Java - Synchronized Method And Block
  6. How to Read Input From Console in Java
  7. How to Create PDF From XML Using Apache FOP
  8. Lambda Expression Examples in Java

1 comment:

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

    ReplyDelete