Java Exception finally keyword

Introduction

finally marks a block of code that will be execute whether or not an exception is thrown.

If a finally block is associated with a try, the finally block will be executed after the try.

public class Main {
  // Throw an exception out of the method. P
  static void myMethodA() {
    try {/*from   w  w  w .j  a  v  a 2s  .  c o m*/
      System.out.println("inside myMethodA");
      throw new RuntimeException("demo");
    } finally {
      System.out.println("myMethodA's finally");
    }
  }

  // Return from within a try block.
  static void myMethodB() {
    try {
      System.out.println("inside myMethodB");
      return;
    } finally {
      System.out.println("myMethodB's finally");
    }
  }

  // Execute a try block normally.
  static void myMethodC() {
    try {
      System.out.println("inside myMethodC");
    } finally {
      System.out.println("myMethodC's finally");
    }
  }

  public static void main(String args[]) {
    try {
      myMethodA();
    } catch (Exception e) {
      System.out.println("Exception caught");
    }

    myMethodB();
    myMethodC();
  }
}



PreviousNext

Related