Skip to content

Instantly share code, notes, and snippets.

@ishiis
Created March 25, 2018 05:21
Show Gist options
  • Save ishiis/bc0c49800e279e3a2e2c1cddbe947e5d to your computer and use it in GitHub Desktop.
Save ishiis/bc0c49800e279e3a2e2c1cddbe947e5d to your computer and use it in GitHub Desktop.

finally -> try

public class Example {
  public static void main(String... args) {
    System.out.println(testFinally());
  }

  public static String testFinally() {
    try{
      return "try";
    } catch(Exception e) {
      return "catch";
    } finally {
      System.out.println("finally");
    }
  }
}
$ javac Example.java && java Example
finally
try

finally -> catch

public class Example {
  public static void main(String... args) {
    System.out.println(testFinally());
  }

  public static String testFinally() {
    try{
      throw new NullPointerException("NPE");
    } catch(Exception e) {
      return "catch";
    } finally {
      System.out.println("finally");
    }
  }
}
$ javac Example.java && java Example
finally
catch

try-finally -> finally -> try-catch

public class Example {
  public static void main(String... args) {
    System.out.println(testFinally());
  }

  public static String testFinally() {
    try{
      try {
        throw new NullPointerException("NPE");
      } catch(Exception e) {
        return "try-catch";
      } finally {
        System.out.println("try-finally");
      }
    } catch(Exception e) {
      return "catch";
    } finally {
      System.out.println("finally");
    }
  }
}
$ javac Example.java && java Example
try-finally
finally
try-catch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment