有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java默认异常处理程序的工作原理

当我们试着运行下面的程序时,我们得到的错误是Exception in thread "main" java.lang.ArithmeticException: / by zero

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

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


共 (2) 个答案

  1. # 1 楼答案

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

    就你而言:

    在异常之后,它进入线程类

         /**
         * 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 UncaughtheException-因为没有定义exceptionHandler,所以它转到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);
                }**
            }
        }
    
  2. # 2 楼答案

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

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