關于Java異常的疑問
問題描述
眾所周知下面的代碼編譯不過:
public class test{ private static void haha(){throw new Exception(); } public static void main(String[] args) {haha();return; }}
javac test.java
未報告的異常錯誤Exception; 必須對其進行捕獲或聲明以便拋出。
但是下面的代碼沒有進行錯誤處理,卻能夠通過編譯:
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異常,運行時異常,所以不需要手動處理
相關文章:
1. bootstrp是col-md-12列的,只有col-md-10有內容,可以讓沒有內容的不占據位置嗎;2. wordpress里,這樣的目錄列表是屬于小工具還是啥?3. 常量在外面不加引號會報錯。4. mysql federated引擎無法開啟5. android - Genymotion 微信閃退 not find plugin.location_google.GoogleProxyUI6. sublime text3安裝package control失敗7. mysql 為什么主鍵 id 和 pid 都市索引, id > 10 走索引 time > 10 不走索引?8. python如何設置一個隨著系統時間變化的動態變量?9. python 3.4 error: Microsoft Visual C++ 10.0 is required10. MySQL 使用 group by 之后然后 IFNULL(COUNT(*),0) 為什么還是會獲得 null
