異常是 java 程序中經常遇到的問題,我想每一個 java 程序員都討厭異常,一 個異常就是一個 bug,就要花很多時間來定位異常問題。
1、nullpointerexception
空指針異常,操作一個 null 對象的方法或屬性時會拋出這個異常。具體看上篇文章:空指針常見案例。
2、outofoutofmemoryerror
內存出現異常的一種異常,這不是程序能控制的,是指要分配的對象的內存超出了當前最大的堆內存,需要調整堆內存大小(-xmx)以及優化程序。
3、ioexception
io,即:input, output,我們在讀寫磁盤文件、網絡內容的時候經常會生的一種異常,這種異常是受檢查異常,需要進行手工捕獲。
如文件讀寫會拋出 ioexception:
1
2
|
public int read() throws ioexception public void write( int b) throws ioexception |
4、filenotfoundexception
文件找不到異常,如果文件不存在就會拋出這種異常。
如定義輸入輸出文件流,文件不存在會報錯:
1
2
|
public fileinputstream(file file) throws filenotfoundexception public fileoutputstream(file file) throws filenotfoundexception |
filenotfoundexception 其實是 ioexception 的子類,同樣是受檢查異常,需要進行手工捕獲。
5、classnotfoundexception
類找不到異常,java開發中經常遇到,是不是很絕望?這是在加載類的時候拋出來的,即在類路徑下不能加載指定的類。
看一個示例:
1
2
3
4
5
6
7
8
|
public static <t> class <t> getexistingclass(classloader classloader, string classname) { try { return ( class <t>) class .forname(classname, true , classloader); } catch (classnotfoundexception e) { return null ; } } |
它是受檢查異常,需要進行手工捕獲。
6、classcastexception
類轉換異常,將一個不是該類的實例轉換成這個類就會拋出這個異常。
如將一個數字強制轉換成字符串就會報這個異常:
1
2
|
object x = new integer( 0 ); system.out.println((string)x); |
這是運行時異常,不需要手工捕獲。
7、nosuchmethodexception
沒有這個方法異常,一般發生在反射調用方法的時候,如:
1
2
3
4
5
6
7
8
|
public method getmethod(string name, class <?>... parametertypes) throws nosuchmethodexception, securityexception { checkmemberaccess(member. public , reflection.getcallerclass(), true ); method method = getmethod0(name, parametertypes, true ); if (method == null ) { throw new nosuchmethodexception(getname() + "." + name + argumenttypestostring(parametertypes)); } return method; } |
它是受檢查異常,需要進行手工捕獲。
8、indexoutofboundsexception
索引越界異常,當操作一個字符串或者數組的時候經常遇到的異常。
例:一個arraylist數組中沒有元素,而你想獲取第一個元素,運行是就會報此類型的錯誤。
1
2
3
4
5
6
|
public class test{ public static void main(args[] ){ list<string> list = new arraylist<>(); system.out.println(list.get( 0 )); } } |
它是運行時異常,不需要手工捕獲。
9、arithmeticexception
算術異常,發生在數字的算術運算時的異常,如一個數字除以 0 就會報這個錯。
1
|
double n = 3 / 0 ; |
這個異常雖然是運行時異常,可以手工捕獲拋出自定義的異常,如:
1
2
3
4
5
6
7
8
9
|
public static timestamp from(instant instant) { try { timestamp stamp = new timestamp(instant.getepochsecond() * millis_per_second); stamp.nanos = instant.getnano(); return stamp; } catch (arithmeticexception ex) { throw new illegalargumentexception(ex); } } |
10、sqlexception
sql異常,發生在操作數據庫時的異常。
如下面的獲取連接:
1
2
3
4
5
6
7
|
public connection getconnection() throws sqlexception { if (getuser() == null ) { return drivermanager.getconnection(url); } else { return drivermanager.getconnection(url, getuser(), getpassword()); } } |
又或者是獲取下一條記錄的時候:
1
|
1 boolean next() throws sqlexception; |
它是受檢查異常,需要進行手工捕獲。
以上所述是小編給大家介紹的十個常見的java異常出現原因詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/aiitzzx0116/p/10505476.html