Finally Block in Java

Finally Block in Java with Examples

In this article, I am going to discuss the Finally block in Java with Examples. Please read our previous article where we discussed Exception Handling in Java. At the end of this article, you will understand the following pointers in detail which are related to Java Finally block.

  1. What is finally block in Java?
  2. Why we need finally block in real-time applications?
  3. Try/Catch/Finally Examples with test cases
  4. Try/Finally Examples with test cases
  5. How JVM execute try-catch-finally block in java?
  6. What is an unreachable statement in Java?
What is finally block in Java?

Finally establishes a block that definitely executes statements placed in it. Statements that are placed in finally block are always executed irrespective of the way the control is coming out from the try block either by completing normally or throwing exceptions by catching or not catching.

Why we need finally block in real-time applications?

As per the coding standard in the finally block we should write resource releasing logic or clean up code.

Resource releasing logic means unreferenced objects that are created in the try block. For example, in real-time projects, we create JDBC objects in the try block and at the end of the try block, we must close these objects. Since the statements written in try and catch block are not guaranteed to be executed we must place them in the finally block.

For example, if we want to close JDBC objects such as Connection object, ResultSet object, etc we must call the close() method in both try as well as in catch block to guarantee its execution. Instead of placing the same close() method call statements in multiple places if we write it in the finally block it is always executed irrespective of the exception raised or not raised.

Syntax to use Finally block in Java:

We can use finally in two ways

  1. try/catch/finally
  2. try/finally
Try/Catch/Finally:

We use this syntax to catch the exception and also to execute some statements definitely

Try Catch Finally in Java

Try/Finally:

We use this syntax if we don’t want to catch the exception but if we want to execute some statements definitely. In this case, program execution is terminated abnormally.

Try Finally in Java

Example: try/catch/finally without exception

In the below example, we have implemented the try, catch and finally block. We also place one statement after the finally block. When we execute the below example, first it will execute the try block. As there is no exception in the try block, so the catch block will not be executed, and then finally block will execute. Once the finally block executed, then the statement present after the finally block gets executed. Run the program and see the output.

public class Main
{
  public static void main (String[]args)
  {
    try
    {
      System.out.println ("in try");
    }
    catch (ArithmeticException ae)
    {
      System.out.println ("in catch");
    }
    finally
    {
      System.out.println ("in finally");
    }
    System.out.println ("after try catch finally");
  }
}

Output:
in try
in finally
after try catch finally

Example: try/catch/finally with exception and catch block is matched

In the below example, we have implemented try, catch and finally block. We also placed one statement after the finally block. When we execute the below code, it will execute the try block first. And in the try block, one exception has occurred i.e. Arithmetic Exception. As soon as the exception occurred, it will search for a catch block to handle that exception, and here, the catch block will be executed. Once the catch block completes its execution, then the finally block will execute. Once the finally block executed, then the statement present after the finally block gets executed. Run the program and see the output for better understanding.

public class Main
{
  public static void main (String[]args)
  {
    try
    {
      System.out.println ("in try");
      System.out.println (10 / 0);
    }
    catch (ArithmeticException ae)
    {
      System.out.println ("in catch");
    }
    finally
    {
      System.out.println ("in finally");
    }
    System.out.println ("after try catch finally");
  }
}

Output:
in try
in catch
in finally
after try catch finally

Example: try/catch/finally with exception and catch block is not matched

In the below example, we have implemented try, catch and finally block. When we execute the following example, it will start execution from the try block. And in the try block, one exception has occurred i.e. Arithmetic Exception. As soon as the exception occurred, the controller will search for a catch block to handle that exception. But there is no catch block to handle the Arithmetic Exception. So, it will then execute the finally block and throw the exception.  Here, the statement present after the finally will not be executed. Run the application and see the output for better understanding.

public class Main
{
  public static void main (String[]args)
  {
    try
    {
      System.out.println ("in try");
      System.out.println (10 / 0);
    }
    catch (NullPointerException npe)
    {
      System.out.println ("in catch");
    }
    finally
    {
      System.out.println ("in finally");
    }
    System.out.println ("after try cat finally");
  }
}
Output:

Finally block in Java with Examples

Example: try/finally without exception

In the below example, we have implemented try and finally block. When we execute the following example. first, it will execute the try block and then it will execute the finally block. Once the finally block executed, then it will execute the statement present after the finally block. Run the application and see the output for better understanding.

public class Main
{
  public static void main (String[]args)
  {
    try
    {
      System.out.println ("in try");
    }
    finally
    {
      System.out.println ("in finally");
    }
    System.out.println ("after try catch finally");
  }
}

Output:
in try
in finally
after try catch finally

Example: try/finally with exception

In the below example, we have implemented try and finally block. When we execute the following example. first, it will execute the try block and in the try block exception has been occurred. And there is no catch block at all. So, it will then execute the finally block and throw an exception. In this case, it will not execute the statement present after the finally block. Run the program and see the output for better understanding.

public class Main
{
  public static void main (String[]args)
  {
    try
    {
      System.out.println ("in try");
      System.out.println (10 / 0);
    }
    finally
    {
      System.out.println ("in finally");
    }
    System.out.println ("after try cat finally");
  }
}
Output:

Finally block in Java with Examples

Rules for writing try-catch-finally Block
  1. Try must be followed by either catch block or finally block or both.
  2. The catch must be followed by either catch block or finally block
  3. The catch must precede by either catch block or try block
  4. Finally must precede by either catch block or try block
  5. We can write only one finally statement and try block and many catch blocks in the try-catch-finally chain.
  6. Nesting try-catch-finally is also possible.
  7. When we write multiple catch blocks if Exception is not having any Is-A relation then we can write catch block in any order otherwise we must write catch block in order like first child class and follow by the parent class.
  8. We cannot write two catch blocks that are going to catch the same Exceptions.
How JVM execute try-catch-finally block in java?

First, it will execute the statements written before try-catch blocks next JVM will enter into try block and if no exception occurred then it will execute all the statements of the try block and it will skip all the catch block and control will be given after try-catch blocks.

JVM will enter into try block and if an exception occurred then it will skip the remaining statements of try block and control will be given to any one of the matching catch blocks and executes the statements available in the catch block and the next control will be given after try-catch blocks.

Note:
  1. When an Exception occurred then control will be given to any of the matching catch blocks and the remaining catch blocks will be skipped and control will be given after try-catch blocks.
  2. If no catch block is matching then JVM will call or invoke “Default Exception Handler” and which always causes abnormal termination.
  3. If the Exception occurred or not in both the cases finally block will be executed.
What is an unreachable statement in Java?

If we place the return statement in the finally block and if we can place statement after finally block it leads to CE: “unreachable statements”. Let us see a program for better understanding

public class Main
{
  public static void main (String[]args)
  {
    System.out.println (m1 ());
  }
  static int m1 ()
  {
    try
    {
      System.out.println ("in try");
      return 10;
    }
    catch (ArithmeticException ae)
    {
      System.out.println ("in catch");
      return 20;
    }
    finally
    {
      System.out.println ("in finally");
      return 30;
    }
    System.out.println ("after try catch finally");	//unreachable statement
  }
}
Output:

What is an unreachable statement in Java

Difference Between Final, Finally and Finalize
finalfinallyfinalize
The Final is used to apply restrictions on class, method, and variable. The final class can’t be inherited, the final method can’t be overridden and the final variable value can’t be changed.Finally is used to place important code, it will be executed whether an exception is handled or not.Finalize is used to perform clean-up processing just before the object is garbage collected.
The Final is a keyword.Finally is a block.Finalize is a method.

In the next article, I am going to discuss throw and throws keywords in Java with examples. Here, in this article, I try to explain the Finally block in Java with Examples. I hope you enjoy this Finally block in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Finally block in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *