What is the use of the finally block?

Finally is the block of code that executes always. The code in finally block will execute even if anexception is occurred. finally will not execute when the user calls System.exit().

finally creates a block of code that will be executed after a try/catch block has completed.

The finally block will execute even if no catch statement matches the exception.

 

finally block can be useful for closing file handles and freeing up any other resources. The finally clause is optional.

 

Example

 

public class Main {

  // Through an exception out of the method.

  static void methodC() {

    try {

      System.out.println("inside methodC");

      throw new RuntimeException("demo");

    } finally {

      System.out.println("methodC finally");

    }

  }

 

  // Return from within a try block.

  static void methodB() {

    try {

      System.out.println("inside methodB");

      return;

    } finally {

      System.out.println("methodB finally");

    }

  }

 

  // Execute a try block normally.

  static void methodA() {

    try {

      System.out.println("inside methodA");

    } finally {

      System.out.println("methodA finally");

    }

  }

 

  public static void main(String args[]) {

    try {

      methodC();

    } catch (Exception e) {

      System.out.println("Exception caught");

    }

    methodB();

    methodA();

  }

}