当使用 try/catch block 时,我们可以使用 e.printStacktrace()
方法在 catch block 中打印堆栈跟踪。
如果出现未处理的异常,仍会打印堆栈跟踪。
谁在控制台上打印堆栈跟踪?以及如何?
最佳答案
如果在您正在查看的代码中未在 Java 中(通过 catch block )明确捕获异常,则会发生以下情况:
异常将向上传播调用堆栈,直到它找到另一个 catch block 来处理它。如果是这样,太好了。如果它到达堆栈的顶部并且没有 catch block 来处理它,那么:
它由指定为 uncaught exception handler for that thread 的任何内容处理.这是一段明确设置为在这种情况发生时运行的代码块。如果没有指定处理程序,则:
它将调用
ThreadGroup
上的uncaughtException()
。根据其 Javadoc , 这会执行以下操作:- If this thread group has a parent thread group, the uncaughtException method of that parent is called with the same two arguments.
- Otherwise, this method checks to see if there is a default uncaught exception handler installed, and if so, its uncaughtException method is called with the same two arguments.
- Otherwise, this method determines if the Throwable argument is an instance of ThreadDeath. If so, nothing special is done. Otherwise, a message containing the thread's name, as returned from the thread's getName method, and a stack backtrace, using the Throwable's printStackTrace method, is printed to the standard error stream.
粗体是我的,默认情况下,这是负责打印堆栈跟踪的行为。
顺便说一句,如果您愿意,您可以实际验证最后一部分 - 像这样的东西将打印一个(简短的)堆栈跟踪,正如您所期望的:
public static void main(String[] args) throws Throwable {
throw new Throwable();
}
Exception in thread "main" java.lang.Throwable at javaapplication6.JavaApplication6.main(JavaApplication6.java:18)
然而,根据上述文档,这不会打印任何内容:
public static void main(String[] args) throws Throwable {
throw new ThreadDeath();
}
关于java - 如果 java 中出现未处理的异常,谁打印异常堆栈跟踪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48903792/