gpt4 book ai didi

java - 异常处理输出消息

转载 作者:行者123 更新时间:2023-12-01 19:06:05 26 4
gpt4 key购买 nike

我编写了下面的代码,摘自 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com