關(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; 必須對其進行捕獲或聲明以便拋出。
但是下面的代碼沒有進行錯誤處理,卻能夠通過編譯:
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. javascript - sublime快鍵鍵問題2. javascript - immutable配合react提升性能?3. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化4. 配置Apache時,添加對PHP的支持時語法錯誤5. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~6. javascript - nodejs關(guān)于進程間發(fā)送句柄的一點疑問7. javascript - 移動端上不能實現(xiàn)拖拽布局嗎?8. phpstudy8.1支持win11系統(tǒng)嗎?9. 實現(xiàn)bing搜索工具urlAPI提交10. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問?

網(wǎng)公網(wǎng)安備