Throwable是Java錯誤處理的父類,有兩個子類:Error和Exception。
Error:無法預期的嚴重錯誤,導致JVM虛擬機無法繼續執行,幾乎無法恢復捕捉的
Exception:可恢復捕捉的。java健壯程序的手段。
Java提供了兩類主要的異常:runtime exception和checked exception (編譯時被檢查的異常)。
checked exception (編譯時被檢查的異常):JAVA編譯器強制要求我們必需對出現的這些異常進行catch或throws。所以,面對這種異常不管我們是否願意,只能寫一大堆catch塊或throws去處理可能的異常。
如IO異常,以及SQL異常等。
runtime exception:編譯通過,但運行通不過,出現RuntimeException,通常是程序員出錯。虛擬機接管會終止線程或主程序。如錯誤的類型轉換、數組越界訪問和訪問空指針等
最常見到的runtime exception
1、NullPointerException:
int a1[]=null;
System.out.print(a1[2]);
2、ArrayIndexOutOfBoundsException
int a[]={2,3,5,32,6};
for (int i = 0; i <6; i++)
{
System.out.print(a[i]);
}
3、ClassCastException
Object i=new Integer(1);
System.out.println((String)i);
4、ArithmeticException
int a=5/0;
5、NegativeArraySizeException
String[] s=new String[-10];