2014-12-27 33 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); 
      }** 
     } 
    }