When exception is thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method. Depending upon how the method is coded, the method may return prematurely. For example, if a method opens a database connection on entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism the finally keyword is designed to address this contingency.

"Finally" creates a block of code that will be executed after try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown.

If an exception is thrown, finally block will execute even if no catch statements matches the exception. Finally is guaranteed to execute, even if no exceptions are thrown. Finally block is an ideal position for closing the resources such as file handle or a database connection etc.

 public class FinallyDemo {

  static void procA(){

    try{
      System.out.println("inside procA");
      throw new RuntimeException("demo");
      
    }finally{
      System.out.println("procA's finally");
    }
  }

  //Return from with in a try block.
  static void procB(){

    try{
      System.out.println("inside procB");
      return;
    }
    finally{
      System.out.println("procB's finally");
    }
  }

  //Execute a try block normally.
  static void procC(){

    try{
      System.out.println("inside procC");
    }
    finally{
      System.out.println("procC's finally");
    }  
  }

  public static void main(String[] args) {

    try{
      procA();
    }catch(Exception e){
      System.out.println("Exception caught");
      
    }

    procB();
    procC();

  }

}

Output Screen:

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's final