關(guān)于Java異常的疑問
問題描述
眾所周知下面的代碼編譯不過:
public class test{ private static void haha(){throw new Exception(); } public static void main(String[] args) {haha();return; }}
javac test.java
未報告的異常錯誤Exception; 必須對其進(jìn)行捕獲或聲明以便拋出。
但是下面的代碼沒有進(jìn)行錯誤處理,卻能夠通過編譯:
public class test{ public static void main(String[] args) {String s = new String('test');System.out.println(s.substring(0,6));return; }}
javac test.javajava test
Exception in thread 'main' java.lang.StringIndexOutOfBoundsException: String index out of range: 6at java.lang.String.substring(Unknown Source)at test.main(test.java:4)
請問這是什么原因?
問題解答
回答1:StringIndexOutOfBoundsException繼承了RuntimeException,不需要顯式地聲明處理。
回答2:第一個拋出的是Exception是checked異常,也就是編譯器異常,所以必須手動處理。第二個拋出的StringIndexOutOfBoundsException是unchecked異常,運行時異常,所以不需要手動處理
相關(guān)文章:
1. mysql - sql 左連接結(jié)果union右連接結(jié)果,導(dǎo)致重復(fù)性計算怎么解決?2. mysql 遠(yuǎn)程連接出錯10060,我已經(jīng)設(shè)置了任意主機(jī)了。。。3. 默認(rèn)輸出類型為json,如何輸出html4. 數(shù)組排序,并把排序后的值存入到新數(shù)組中5. mysql的主從復(fù)制、讀寫分離,關(guān)于從的問題6. 怎么能做出標(biāo)簽切換頁的效果,(文字內(nèi)容隨動)7. php多任務(wù)倒計時求助8. mysql怎么表示兩個字段的差9. PHP訂單派單系統(tǒng)10. MySQL的聯(lián)合查詢[union]有什么實際的用處
