默认异常处理程序如何工作

Man*_*mar 3 java exception

当我们尝试运行以下程序时,我们会收到以下错误 Exception in thread "main" java.lang.ArithmeticException: / by zero

class excp {
  public static void main(String args[]) {
    int x = 0;
    int a = 30/x;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是当我们问某人这些是如何工作的时,他告诉我这个异常是由默认异常处理程序捕获的,所以我无法理解这个默认异常处理程序是如何工作的。请详细说明这一点。

use*_*716 5

引用 JLS 11 :

30/x - 违反了 Java 语言的语义约束 - 因此会发生异常。

If no catch clause that can handle an exception can be found, 
then the **current thread** (the thread that encountered the exception) is terminated
Run Code Online (Sandbox Code Playgroud)

在终止之前 - 未捕获的异常按照以下规则处理:

(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.
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

异常发生后进入Thread类

     /**
     * Dispatch an uncaught exception to the handler. This method is
     * intended to be called only by the JVM.
     */
    private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }
Run Code Online (Sandbox Code Playgroud)

然后它按照规则 2 转到 ThreadGroup uncugthException - 由于没有定义异常处理程序,因此它转到 Else if - 并且线程被终止

public void uncaughtException(Thread t, Throwable e) {
        if (parent != null) {
            parent.uncaughtException(t, e);
        } else {
            Thread.UncaughtExceptionHandler ueh =
                Thread.getDefaultUncaughtExceptionHandler();
            if (ueh != null) {
                ueh.uncaughtException(t, e);
            } **else if (!(e instanceof ThreadDeath)) {
                System.err.print("Exception in thread \""
                                 + t.getName() + "\" ");
                e.printStackTrace(System.err);
            }**
        }
    }
Run Code Online (Sandbox Code Playgroud)