【Java中的finally 】

1. 在try中return后,finally是否会执行?

  是

  2. 在try中throw exception后,finally是否会执行?

  是

  3. 在try中System.exit(0)后,finally是否会执行?

  否

  例子:

  public class Test2 {

  public static void main(String[] args) throws Exception {

  returnValue();

  tryException();

  exit();

  }

  public static int returnValue() {

  try{

  return 0;

  } finally {

  System.out.println("finally in returnValue");

  }

  }

  public static void tryException() throws Exception {

  try{

  throw new Exception("My exception");

  } finally {

  System.out.println("finally in tryException");

  }

  }

  public static void exit() {

  try{

  System.exit(0);

  } finally {

  System.out.println("finally in exit");

  }

  }

  }

  以下是屏幕输出:

  finally in returnValue

  finally in tryException

  Exception in thread "main" java.lang.Exception: My exception

  at other.Test2.tryException(Test2.java:21)

  at other.Test2.main(Test2.java:7)

posted @ 2013-09-28 15:32  豆豆逗逗  阅读(127)  评论(0编辑  收藏  举报