關于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. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””2. Span標簽3. css - 求推薦適用于vue2的框架 像bootstrap這種類型的4. docker-machine添加一個已有的docker主機問題5. android新手一枚,android使用httclient獲取服務器端數據失敗,但是用java工程運行就可以成功獲取。6. css - 關于div自適應問題,大家看圖吧,說不清7. angular.js使用$resource服務把數據存入mongodb的問題。8. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?9. python - django如何每次調用標簽的時候都取隨機數據10. SessionNotFoundException:會話ID為null。調用quit()后使用WebDriver嗎?(硒)
