Detail the finally clause in Java exception handling

  • 2020-04-01 04:12:41
  • OfStack

When an exception is thrown, the execution of the usual method makes a steep nonlinear turn. Depending on how the method is encoded, exceptions can even cause the method to return too soon. This is a problem in some ways. For example, if a method opens a file entry, closes it, and then exits, you don't want the code that closes the file to be bypassed by the exception handling mechanism. The finally keyword is designed to handle this contingency.

Finally creates a code block. This block of code is executed after one try/catch block completes and before another try/catch appears. The finally block executes with or without an exception thrown. If an exception is thrown, a finally is executed even without a catch clause matching the exception. A method will return from a try/catch block to any time the calling program passes an uncaught exception or an explicit return statement, and the finally clause will execute until the method returns. This is useful in closing the file handle and freeing up any other resources that are allocated at the beginning of the method. The finally clause is optional and can be available or not. However, each try statement requires at least one catch or finally clause.

The following example shows three different exit methods. Each executes the finally clause:


// Demonstrate finally.
class FinallyDemo {
  // Through an exception out of the method.
  static void procA() {
    try {
      System.out.println("inside procA");
      throw new RuntimeException("demo");
    } finally {
      System.out.println("procA's finally");
    }
  }

  // Return from within 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();
  }
}

In this example, procA() interrupts the try prematurely by throwing an exception. The Finally clause is executed at exit. The try statement for procB() exits with a return statement. The finally clause executes before procB() returns. In procC (), the try statement executes normally with no errors. However, the finally block will still execute.

Note: if the finally block is used in conjunction with a try, the finally block is executed before the try ends.

Here is the output from the above program:


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


Related articles: