首頁  >  問答  >  主體

关于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.java
java test

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
        at java.lang.String.substring(Unknown Source)
        at test.main(test.java:4)

请问这是什么原因?

PHP中文网PHP中文网2744 天前574

全部回覆(2)我來回復

  • 巴扎黑

    巴扎黑2017-04-18 10:51:21

    StringIndexOutOfBoundsException繼承了RuntimeException,不需要明確地宣告處理。

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-18 10:51:21

    第一個拋出的是Exception是checked異常,也就是編譯器異常,所以必須手動處理。第二個拋出的StringIndexOutOfBoundsException是unchecked異常,執行時異常,所以不需要手動處理

    回覆
    0
  • 取消回覆