java中异常处理的输出不一致
当我多次运行此程序时,我得到了不同的输出:java中异常处理的输出不一致,java,Java,当我多次运行此程序时,我得到了不同的输出: public class Demo { public static void main(String[] args) { try { System.out.println("try block"); int a = 10 / 0; } catch (Exception e) { System.out.println("catch block"); int a = 10 /
public class Demo {
public static void main(String[] args) {
try {
System.out.println("try block");
int a = 10 / 0;
} catch (Exception e) {
System.out.println("catch block");
int a = 10 / 0;
} finally {
System.out.println("finally block");
int a = 10 / 0;
}
}
}
第一个输出:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at kd.demo.Demo2.main(Demo2.java:14)
try block
catch block
finally block
第二输出:
Exception in thread "main" try block
catch block
finally block
java.lang.ArithmeticException: / by zero
at kd.demo.Demo2.main(Demo2.java:14)
第三输出:
Exception in thread "main" try block
catch block
finally block
java.lang.ArithmeticException: / by zero
at kd.demo.Demo2.main(Demo2.java:14)
当我多次编译和执行这个程序时,我得到了不同的输出。大多数时候,我得到了第三个,这不是一个问题。但是,我对其他输出(第一个和第二个)感到困惑。您同时写入System.out(您的println语句)和System.err(将从finally块中引发的未捕获异常打印的堆栈跟踪) 交错排列在屏幕上的显示顺序相当不确定
您可以通过将消息发送到System.err而不是System.out来“修复”此问题。然后所有内容都将进入同一个流。您正在写入System.out(您的println语句)和System.err(将从finally块中引发的未捕获异常打印的堆栈跟踪) 交错排列在屏幕上的显示顺序相当不确定
您可以通过将消息发送到System.err而不是System.out来“修复”此问题。然后所有的东西都会流向同一条流。第二条和第三条有什么区别?第二条和第三条有什么区别?