java - 如果 java 中出现未处理的异常,谁打印异常堆栈跟踪?

标签 java exception

当使用 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/

相关文章:

java - 如何将 AAR 转换为 JAR

java - 如何解决 "injection of autowired dependencies failed"问题?

java - 反转默认的 Java LinkedList

exception - 选择带有日志异常的 "Add External JARs..."时不显示 FileDialog

java - 为什么 JUnit 调用 "object"而不是 "exception"?

Java:通过 Ldap 在 Active Directory 中创建用户时出现错误代码 53

java - fragment 之间通信的正确方式

java - 接口(interface)中方法签名异常

c# - 带等待的 ThreadAbortException

android - 陈旧数据异常 : Attempted to access a cursor after it has been closed