未处理的异常的输出与程序的输出混合

时间:2018-05-26 16:33:26

标签: java exception exception-handling

当我在java中运行这个程序时

package test;

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("line"+i);
        }
        System.out.flush();
        int x=1/0;
    }
}

我希望有这样的输出:

line0
line1
line2
line3
line4
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at test.Main.main(Main.java:8)

Process finished with exit code 1

但输出看起来像这样:

Exception in thread "main" java.lang.ArithmeticException: / by zero
line0
    at test.Main.main(Main.java:8)
line1
line2
line3
line4

Process finished with exit code 1

在我再次运行之后:

line0
Exception in thread "main" java.lang.ArithmeticException: / by zero
line1
    at test.Main.main(Main.java:9)
line2
line3
line4

Process finished with exit code 1

等等。行或异常消息随机混合输出。 我尝试在System.out.flush();之前添加int x=1/0;,但它没有帮助。 当我创建自己的Exception(它扩展了RuntimeException)和我发出NullPointerException时,也会发生这种情况。为什么会发生这种情况?我该如何解决?

1 个答案:

答案 0 :(得分:3)

这是因为使用System.err打印的例外情况与PrintStream不同System.out。如果您希望使用System.out打印例外,则可以拨打System#setErr

System.setErr(System.out);

for (int i = 0; i < 5; i++) {
    System.out.println("line"+i);
}

int x = 1 / 0;

输出:

line0
line1
line2
line3
line4
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Test/test.Test.main(Test.java:13)