對于程序中出現(xiàn)異常,是很多程序員不想看到的情況,因為這就需要我們?nèi)ゲ樵儺惓5脑颍缓筮M行一些處理異常的操作。在Java數(shù)組操作時,也會有一些異常情況的發(fā)生。這里我們羅列出了兩種:ClassCastException和NullPointerException,下面我們來看一下具體的介紹。
1、異常種類
檢查型異常和非檢查型異常的主要區(qū)別在于其處理方式。檢查型異常都需要使用try,catch 和finally 關(guān)鍵字在編譯器進行處理,否則會出現(xiàn)編譯器報錯。對于非檢查型異常則不需要這樣做。Java中所有繼承 Exception 的類的異常都是檢查型異常,所有繼承RuntimeException 的異常都被稱為非檢查型異常。
2、ClassCastException
類轉(zhuǎn)換異常,將一個不是該類的實例轉(zhuǎn)換成這個類就會拋出這個異常。
如將一個數(shù)字強制轉(zhuǎn)換成字符串就會報這個異常:
1
2
|
Object x = new Integer( 0 ); System.out.println((String)x); |
這是運行時異常,不需要手工捕獲。
3、空指針異常NullPointerException
操作一個 null 對象的方法或?qū)傩詴r會拋出這個異常。
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()); |
提示:一旦程序出現(xiàn)異常,未處理時,就終止執(zhí)行。
內(nèi)容擴展:
- 算術(shù)異常類:ArithmeticExecption
- 空指針異常類:NullPointerException
- 類型強制轉(zhuǎn)換異常:ClassCastException
- 數(shù)組負(fù)下標(biāo)異常:NegativeArrayException
- 數(shù)組下標(biāo)越界異常:ArrayIndexOutOfBoundsException
- 違背安全原則異常:SecturityException
- 文件已結(jié)束異常:EOFException
- 文件未找到異常:FileNotFoundException
- 字符串轉(zhuǎn)換為數(shù)字異常:NumberFormatException
- 操作數(shù)據(jù)庫異常:SQLException
- 輸入輸出異常:IOException
- 方法未找到異常:NoSuchMethodException
到此這篇關(guān)于java數(shù)組中的異常類型整理的文章就介紹到這了,更多相關(guān)java數(shù)組中的異常有哪些內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.py.cn/java/shuzu/23820.html