2014-12-27 32 views
0

当我们尝试运行下面的程序,然后我们得到的错误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异常处理程序如何工作。 Plz详细说明了这一点。

+1

http://www.javamex.com/tutorials/exceptions/exceptions_uncaught_handler.shtml – Tom

+0

如果你没有try/catch语句的例外,那么, JVM捕获它。 – OldProgrammer

回答

2

报价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是d efined它去否则,如果 - 和线程终止

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