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

标签 java exception

如果我们在 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/

相关文章:

java - 自定义异常(exception)或空列表

java - 如何创建可变数量的 arrayLists 以及列表中可变数量的项目?

java - 为什么不能取消引用 lambda 表达式?

java - Java中如何获取exe的相对路径

java - 尝试保存嵌套 fragment 的状态时出现异常 [ fragment 不再存在关键 android :target_state]

线程 "main"java.lang.NoClassDefFoundError : javafx/application/Application 中的 JavaFX 异常

java - 如何在MySql DB中插入反斜杠(\)?

java - Android/Java 如何在没有 line2d 的情况下检查矩形和线段是否相交

python-3.x - 在快速 api 中全局捕获 `Exception`

java - java调用多个oracle存储过程并保持数据一致性