java - 异常处理输出消息

标签 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.

最佳答案

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

关于java - 异常处理输出消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10072301/

相关文章:

java - 在 Java 中,如何使用 posix 通配符语法从多个文件中读取数据?

java - 反转字节顺序/更改字节顺序的命令行

java - 无法从 html 表单操作属性调用其余 Web 服务

java - 无法使我的 spring boot 应用程序与 jsp 一起工作

java - 将树节点标记为已选择(Swing)

java - 在链接上使用struts 1 CSRF保护

java - 使用 Google Guava 过滤和转换集合

java - 安卓/Java : How to track progress of InputStream

java - 如何创建一个自定义异常,它在 java 中包装多个异常

java - 如果我使用 org.apache.hadoop.mapreduce(新)API,如何配置 Hadoop MapReduce 映射器输出压缩?