0

我编写了下面的代码,取自 Java How to program 9th Edition - 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.
4

1 回答 1

4

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

于 2012-04-09T11:23:52.323 回答