使用这段代码:
class SimpleException extends Exception {}
public class SimpleExceptionDemo {
public void f() throws SimpleException {
System.out.println("Throw SimpleException from f()");
throw new SimpleException();
}
public static void main(String[] args) {
SimpleExceptionDemo sed = new SimpleExceptionDemo();
try {
sed.f();
} catch(SimpleException e) {
System.err.println("Caught it!");
}
}
}
在某些情况下我有这样的输出:
Caught it!
Throw SimpleException from f()
你知道为什么在“捕获它”之后打印“Throw SimpleException from f()”吗?
最佳答案
您正在两个不同的输出流上打印:
System.out.println("Throw SimpleException from f()");
和
System.err.println("Caught it!");
无法保证来自两个不同流的消息出现的顺序......使用相同的流,就可以了。
如果您对此类问题感兴趣,阅读
可能会很有趣关于java - 当我在 Java 中启动我的个性化异常时,为什么解析器不遵循我的代码顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18913778/