Java Exception finally keyword always run

Introduction

The try block throws an exception and it is caught by a matching catch block.

The finally block will execute right after the catch block executes.

public class Main {
  public static void main(String args[]) {
    try {/* w  ww .ja va  2s. c  om*/
      throw new Exception();
    } catch (Exception e) {
      System.out.println("In catch");
    } finally {
      System.out.println("In finally");
    }
  }
}

The finally clause is executed even if an exception is thrown from the catch statement.


public class Main {
  public static void main(String args[]) throws Exception {
    try {//  www  .j  ava2  s . com
      throw new Exception();
    } catch (Exception e) {
      System.out.println("In catch");
      throw new Exception();
    } finally {
      System.out.println("In finally");
    }
  }
}

Throw exception in try block.


public class Main {
  public static void main(String args[]) throws Exception {
    try {/*from w  w  w .  ja  va  2  s .com*/
      throw new Exception();
    } finally {
      System.out.println("In finally ");
    }
  }
}

A return statement is executed before the try block completes.

Before it returns to caller, the finally block is still executed.

public class Main {
  public static void main(String args[]) {
    try {//w w  w .  ja  va2  s .c o  m
      return;
    } finally {
      System.out.println("In finally ");
    }
  }
}



PreviousNext

Related