异常处理输出消息

时间:2012-04-09 11:07:10

标签: java

我编写了下面的代码,它取自Java如何编写第9版--Paul和Michelle Harvey - 代码工作正常,但问题是每次执行它时,它都会给出不确定的结果,其中异常是处理 - 例如请查看代码段的输出。能帮助我理解为什么会出现这种情况吗?

 public class Test {

    public static void main(String[] args) {

        try {
            // call method throwException
            throwException();
        }// end try

        catch (Exception e) {
            System.out.println("Exception handled in main");
        }// end catch

        // call method doesNotThrowException
        doesNotThrowException();

    }

    private static void throwException() throws Exception {
        try {
            System.out.println("Method throwException.");
            throw new Exception(); // generate exception
        }

        catch (Exception exception) {
            System.err.println("Exception handled in method throwException");
            throw exception;
        }

        // executes regardless of what occurs in try ... catch block
        finally {
            System.err.println("Finally executed in throwException.");
        }
    }// end of method throwException

    private static void doesNotThrowException() {
        try {
            System.out.println("Method doesNotThrowException.");
        }

        // catch does not execute as the method does not throw any exceptions
        catch (Exception exception) {
            System.err.println(exception);
        }// end catch

        // executes regardless of what occurs in try ... catch block
        finally {
            System.err.println("Finally executed in doesNotThrowException");
        }
    }// end of deosNotThrowException

}//end Test Class

输出: 1)

Method throwException.
Exception handled in method throwException
Finally executed in throwException.
Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.

2)

Exception handled in method throwException
Finally executed in throwException.Method throwException.

Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.

1 个答案:

答案 0 :(得分:4)

不同运行的不同输出是因为您使用了2个不同的输出流: out err 。操作系统需要刷新此类I / O流,并且每次运行时都会以不同的方式执行此操作,具体取决于与程序无关的其他因素。操作系统唯一保证的是 out 的顺序和 err 的顺序,但不是它们之间的顺序。