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

时间:2014-12-27 03:32:01

标签: java exception-handling

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

的错误
class excp {
  public static void main(String args[]) {
    int x = 0;
    int a = 30/x;
  }
}

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

2 个答案:

答案 0 :(得分:3)

引用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

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

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

在你的情况下:

异常后进入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);
    }

然后根据规则2转到ThreadGroup uncaugthException - 因为没有定义exceptionHandler,所以如果 - 并且线程被终止则转到Else

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);
            }**
        }
    }

答案 1 :(得分:1)

无论何时在方法内部,如果发生异常,该方法都会创建一个称为异常对象的对象,并将其交给运行时系统 (JVM)。异常对象包含异常类名、异常描述和堆栈跟踪(发生异常的程序的位置)。

运行时系统从发生异常的方法开始搜索,按照与调用方法相反的顺序遍历调用堆栈。如果它找到合适的处理程序,那么它会将发生的异常传递给它。如果运行时系统搜索调用堆栈上的所有方法并且找不到合适的处理程序,则运行时系统将异常对象移交给默认异常处理程序,这是运行时系统的一部分.此处理程序打印异常类名称、异常描述和堆栈跟踪并异常终止程序。