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 exception by catching or not catching.

Why we need finally block in real-time applications?

As per coding standard in 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 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 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
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 cat finally");
  }
}

Output:

try/catch/finally without exception

Example: try/catch/finally with exception and catch block is matched
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 cat finally");
  }
}

Output:

try/catch/finally block in Java with exception and catch block is matched

Example: try/catch/finally with exception and catch block is not matched
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:

try/catch/finally block in Java with exception and catch block is not matched

Example: try/finally without exception
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 cat finally");
  }
}

Output:

Finally block Examples in Java

Example: try/finally with exception
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 Examples in Java

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 followed by the parent class.
  8. We cannot write two catch blocks which 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 remaining statements of try block and control will be given to anyone 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 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 return statement in finally block 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 unreachable statement in Java?

Difference Between Final, Finally and Finalize
final finally finalize
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 *