gpt4 book ai didi

java - 谁实际处理 main 方法中抛出的异常?

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:37 25 4
gpt4 key购买 nike

如果我们在 main 方法中抛出一个异常并且不处理它,它将正常工作。其实

public static void main(String[] args) throws IOException {
throw new IOException(); //OK
}

但 Java 要求在程序中处理任何已检查的异常,因此应该处理 IOException。在这种情况下,谁实际处理 IOException?

请注意,Java 语言规范定义了如果异常包含在包含 catch 子句的 try block 中,则该异常将被处理,该类型是该异常的父类(super class)型。

最佳答案

如果您自己没有采取任何特殊操作来捕获异常,则执行 ThreadGroup 的默认 uncaughtException

这是在 JLS Chapter 11.3 中指定的.

If no catch clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated. Before termination, all finally clauses are executed and the uncaught exception is handled according to the following rules:

  1. If the current thread has an uncaught exception handler set, then that handler is executed.

  2. Otherwise, the method uncaughtException is invoked for the ThreadGroup that is the parent of the current thread. If the ThreadGroup and its parent ThreadGroups do not override uncaughtException, then the default handler's uncaughtException method is invoked.

此外 ThreadGroup.uncaughtException 的 javadoc全文如下:

Called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception, and the thread does not have a specific Thread.UncaughtExceptionHandler installed.

The uncaughtException method of ThreadGroup does the following:

  • 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.

关于java - 谁实际处理 main 方法中抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655981/

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