How default exception handler work

不羁的心 提交于 2019-12-22 18:59:46

问题


When we try to run the following program then we get the error that Exception in thread "main" java.lang.ArithmeticException: / by zero

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

but when we ask somebody how these works, then he tell me that this exception is cautch by the default exception handler, So i could't understand how this defualt exception handler works. Plz elaborate this.


回答1:


Quoting JLS 11 :

30/x - violates the semantic constraint of Java Language - hence the exception will occur.

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 - the uncaught exception is handled as per 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.

In your case :

After the exception it goes into Thread class

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

Then it goes to the ThreadGroup uncaugthException as per Rule 2 - Since no exceptionHandler is defined it goes to Else if - and the thread is terminated

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


来源:https://stackoverflow.com/questions/27664104/how-default-exception-handler-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!