1. 程式人生 > >Java 異常類介紹 從頭(Throwable)說起

Java 異常類介紹 從頭(Throwable)說起

Throwable類

Throwable 類是 Java 語言中所有錯誤或異常的超類。只有當物件是此類(或其子類之一)的例項時,才能通過 Java 虛擬機器或者 Java throw 語句丟擲。只有此類或其子類之一才可以是 catch 子句中的引數型別。

Throwable 有兩個子類: 異常(Exception)、系統錯誤(Error)

Error

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. TheThreadDeath

error, though a "normal" condition, is also a subclass ofError because most applications should not try to catch it. 

Error 是 Throwable 的子類,一個合理的應用程式不應該嘗試捕獲的嚴重問題。

Error是程式無法處理的錯誤,比如OutOfMemoryError、ThreadDeath等。這些異常發生時,Java虛擬機器(JVM)一般會選擇執行緒終止。 

Exception

Exception 屬於應用程式級別的異常,這類異常必須捕捉,Exception體系包括RuntimeException體系和其他非RuntimeException的體系

Exception 分為未檢查異常(RuntimeException)和已檢查異常(UnRuntimeException)

執行時異常(RuntimeException)

RuntimeExceptiony 也稱為unchecked Exceptiony,不需要try...catch...或throws 機制去處理的異常。在執行是JVM就會丟擲異常。

RuntimeRxception類中的註釋如下:

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual

Machine.RuntimeException是在Java虛擬機器的正常操作期間可以丟擲的異常的超類。

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

RuntimeException及其子類都是未檢查的異常。未經檢查的異常不需要在方法或建構函式的throws子句中宣告,因為可以通過執行方法或建構函式向外丟擲未檢查異常。此類異常將由JVM進行處理。

總結了一下JAVA中常見的幾種RuntimeException:

NullPointerException - 空指標引用異常

ClassCastException - 型別強制轉換異常。

IllegalArgumentException - 傳遞非法引數異常。

ArithmeticException - 算術運算異常

ArrayStoreException - 向陣列中存放與宣告型別不相容物件異常

IndexOutOfBoundsException - 下標越界異常

NegativeArraySizeException - 建立一個大小為負數的陣列錯誤異常

NumberFormatException - 數字格式異常

SecurityException - 安全異常

UnsupportedOperationException - 不支援的操作異常

非執行時異常

這裡指的是除RuntimeException以外的所有異常。也稱為受檢異常。

從程式語法角度講是必須進行處理的異常,如果不處理,程式就不能編譯通過。

定義方法時必須宣告所有可能會丟擲的exception; 在呼叫這個方法時,必須捕獲它的checked exception,不然就得把它的exception傳遞下去。