對于程序中出現異常,是很多程序員不想看到的情況,因為這就需要我們去查詢異常的原因,然后進行一些處理異常的操作。在Java數組操作時,也會有一些異常情況的發生。這里我們羅列出了兩種:ClassCastException和NullPointerException,下面我們來看一下具體的介紹。
1、異常種類
檢查型異常和非檢查型異常的主要區別在于其處理方式。檢查型異常都需要使用try,catch 和finally 關鍵字在編譯器進行處理,否則會出現編譯器報錯。對于非檢查型異常則不需要這樣做。Java中所有繼承 Exception 的類的異常都是檢查型異常,所有繼承RuntimeException 的異常都被稱為非檢查型異常。
2、ClassCastException
類轉換異常,將一個不是該類的實例轉換成這個類就會拋出這個異常。
如將一個數字強制轉換成字符串就會報這個異常:
1
2
|
Object x = new Integer( 0 ); System.out.println((String)x); |
這是運行時異常,不需要手工捕獲。
3、空指針異常NullPointerException
操作一個 null 對象的方法或屬性時會拋出這個異常。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//情況一: int [] arr1 = new int []{ 1 , 2 , 3 }; arr1 = null ; System.out.println(arr1[ 0 ]); //情況二: int [][] arr2 = new int [ 4 ][]; System.out.println(arr2[ 0 ][ 0 ]); //情況: String[] arr3 = new String[]{ "AA" , "BB" , "CC" }; arr3[ 0 ] = null ; System.out.println(arr3[ 0 ].toString()); |
提示:一旦程序出現異常,未處理時,就終止執行。
內容擴展:
- 算術異常類:ArithmeticExecption
- 空指針異常類:NullPointerException
- 類型強制轉換異常:ClassCastException
- 數組負下標異常:NegativeArrayException
- 數組下標越界異常:ArrayIndexOutOfBoundsException
- 違背安全原則異常:SecturityException
- 文件已結束異常:EOFException
- 文件未找到異常:FileNotFoundException
- 字符串轉換為數字異常:NumberFormatException
- 操作數據庫異常:SQLException
- 輸入輸出異常:IOException
- 方法未找到異常:NoSuchMethodException
到此這篇關于java數組中的異常類型整理的文章就介紹到這了,更多相關java數組中的異常有哪些內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/java/shuzu/23820.html