import java.text.SimpleDateFormat;
public class ExceptionExer {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddhhMMss");
String date = "20130322110000";

try {

sdf.parse(date);
System.out.println("987654321");
throw new Exception();
} catch (Exception e) {
System.out.println("asdf");
e.printStackTrace();
} finally {
System.out.println("123456789");
}
}
}
代码如上,这样的打印顺序是异常,try块,catch块,finally块,但是如果把new 的Exception()换成一个具体的Exception(比如IllegalAccessException),打印顺序就变成try块,catch块,finally块,异常打印了,请教下这是为什么呢?在线等高手解答exception打印顺序

解决方案 »

  1.   

    每次执行,异常的位置都可能不固定的,下面就是我执行结果987654321
    asdf
    java.lang.IllegalAccessException
    at ExceptionExer.main(ExceptionExer.java:11)
    123456789
    987654321
    asdf
    123456789
    java.lang.Exception
    at ExceptionExer.main(ExceptionExer.java:11)
      

  2.   

    System.out.println();用的是标准输出流:System.out
    e.printStackTrace();用的是标准错误流:System.err
    他们自己内部同步的,你执行无数次,换任何异常,都是try、catch、finally这样的顺序
    但是他们两个是不同步的,和使用什么异常没关系,所以异常的顺序是不定的,你多执行几次就看出来了
      

  3.   

    那应该是e.printStackTrace();是在一个单独的线程中执行的,所以出现的位置相对主线程输出不固定了?
      

  4.   

    谢谢,好吧 我都是换了Exception之后执行,顺序是固定的,没有同一个exception执行多次
      

  5.   

    都是Exception的话,我照样执行两次就这样了java.lang.Exception
    at ExceptionExer.main(ExceptionExer.java:11)
    987654321
    asdf
    123456789987654321
    asdf
    123456789
    java.lang.Exception
    at ExceptionExer.main(ExceptionExer.java:11)