//: c09:FinallyWorks.java
// The finally clause is always executed.
import com.bruceeckel.simpletest.*;class ThreeException extends Exception {}public class FinallyWorks {
  private static Test monitor = new Test();
  static int count = 0;
  public static void main(String[] args) {
    while(true) {
      try {
        // Post-increment is zero first time:
        if(count++ == 0)
          throw new ThreeException();
        System.out.println("No exception");
      } catch(ThreeException e) {
        System.err.println("ThreeException");
      } finally {
        System.err.println("In finally clause");
        if(count == 2) break; // out of "while"
      }
    }
    monitor.expect(new String[] {
      "ThreeException",
      "In finally clause",
      "No exception",
      "In finally clause"
    });
  }
} ///:~我运行的结果是
ThreeException
In finally clause
In finally clause
No exception
请大家帮忙分析一下 ,那种正确??最好对程序进行讲解一下,我看这章有点晕......

解决方案 »

  1.   

    System.err.println("ThreeException");
    System.err.println("In finally clause");
    System.out.println("No exception");
    System.err.println("In finally clause");抛出异常  中断执行 
    catch 捕获异常   打印 ThreeException
    finally中  打印  In finally clause继续循环
    未出现异常 不中断  打印 No exception
    没有异常给catch捕获 
    然后finally  打印 In finally clause循环结束
      

  2.   

    哦 我debug一下也是你那个结果,可我直接点运行就是这个结果
    ThreeException
    In finally clause
    In finally clause
    No exception郁闷不知道什么原因??高手指点 ,我的是eclipse.
      

  3.   

    貌似和线程有关
    做个小实验在Try里占用点时间,结果就不一样~
      

  4.   

    这跟系统处理err和out的顺序有关,如果把所有的err都改成out,就是正常的顺序了:
    ThreeException
    In finally clause
    No exception
    In finally clause一般来说,err是立即输出到显示的,而out是有buffer的,所以显示顺序看上去有问题。
    "By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored."