如果我们在 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:
If the current thread has an uncaught exception handler set, then that handler is executed.
Otherwise, the method
uncaughtException
is invoked for theThreadGroup
that is the parent of the current thread. If theThreadGroup
and its parentThreadGroups
do not overrideuncaughtException
, then the default handler'suncaughtException
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 ofThreadGroup
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 ofThreadDeath
. If so, nothing special is done. Otherwise, a message containing the thread's name, as returned from the thread'sgetName
method, and a stack backtrace, using theThrowable
'sprintStackTrace
method, is printed to the standard error stream.
关于java - 谁实际处理 main 方法中抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655981/