天天看點

java常見異常舉例_java常見異常

運作時異常:指編譯器不要求強制處理的異常。一般是指程式設計時的邏輯錯誤。java.lang.RuntimeException類及它的子類都是運作時異常。

下面舉例幾種常見的運作時異常

ArrayIndexOutOfBoundsException

int arr[] = new int[]{1, 2, 3}

for(int i = 0; i < 4; i++){

System.out.println(arr[i]);// 數組角标越界異常

}

數組角标越界異常:指數組的索引取值超過了本身的數組長度,就會造成越界異常

NullPointerException

int arr[] = new int[] {1, 2, 3};

System.out.println(arr[2]);

arr = null;

System.out.println(arr[2]);//空指針異常

空指針異常:當取一個null的的索引或調用null的方法和屬性時就會産生空指針異常,因為null本身就是空的,調用它的方法或屬性是不存在的。

NumberFormatException

String str = "123";

str = "abc";

Integer i = new Integer(str);// 數字格式轉化錯誤

數字格式轉化異常:當用包裝類轉化一個由數字組成的字元串時,由于字元串不是由數字組成,是以不知道該轉化成什麼數字,進而抛出異常

ClassCastException

Person p = new Person();

Student s = (Student)p;//執行個體類型轉換異常

class Person{}

class Student extends Person{}

執行個體類型轉換異常:當一對具有子父類關系的類進行類型轉換時,如果父類的對象不是多态,那麼強制轉換為子類類型就會報錯,因為并不具有子類的擴充功能

ArithmeticException

int a = 10 / 0

算術異常:指一些計算上的錯誤,零不能做除數

InputMismatchException

Scanner scanner = new Scanner(System.in);

int score = scanner.nextInt();

System.out.println(score);

scanner.close();

輸入不比對異常:指在輸入過程中,沒有輸入比對的資料類型而産生的異常。

編譯時異常:指編譯器要求必須處置的異常。即程式在運作時由于外界因素造成的一般性異常。編譯器要求Java程式必須捕獲或聲明所有編譯時異常

FileNotFoundException

// 檔案未找到異常

File file = new File("hello.txt");

FileInputStream fileInputStream = new FileInputStream(file);

檔案未找到異常:當檔案不存在時出現的異常

異常體系結構

java.lang.Throwable

* |-----java.lang.Error:一般不編寫針對性的代碼進行處理。

* |-----java.lang.Exception:可以進行異常的處理

* |------編譯時異常(checked)

* |-----IOException

* |-----FileNotFoundException

* |-----ClassNotFoundException

* |------運作時異常(unchecked,RuntimeException)

* |-----NullPointerException

* |-----ArrayIndexOutOfBoundsException

* |-----ClassCastException

* |-----NumberFormatException

* |-----InputMismatchException

* |-----ArithmeticException