成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術文章
文章詳情頁

關于Java異常的疑問

瀏覽:113日期:2024-01-31 09:38:16

問題描述

眾所周知下面的代碼編譯不過:

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異常,運行時異常,所以不需要手動處理

標簽: java
相關文章: