關(guān)于Java異常的疑問
問題描述
眾所周知下面的代碼編譯不過:
public class test{ private static void haha(){throw new Exception(); } public static void main(String[] args) {haha();return; }}
javac test.java
未報(bào)告的異常錯(cuò)誤Exception; 必須對(duì)其進(jìn)行捕獲或聲明以便拋出。
但是下面的代碼沒有進(jìn)行錯(cuò)誤處理,卻能夠通過編譯:
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:第一個(gè)拋出的是Exception是checked異常,也就是編譯器異常,所以必須手動(dòng)處理。第二個(gè)拋出的StringIndexOutOfBoundsException是unchecked異常,運(yùn)行時(shí)異常,所以不需要手動(dòng)處理
相關(guān)文章:
1. boot2docker無法啟動(dòng)2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. docker-compose中volumes的問題4. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.5. java - SSH框架中寫分頁時(shí)service層中不能注入分頁類6. nignx - docker內(nèi)nginx 80端口被占用7. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?8. dockerfile - 為什么docker容器啟動(dòng)不了?9. docker容器呢SSH為什么連不通呢?10. 關(guān)于docker下的nginx壓力測試

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