search

Home  >  Q&A  >  body text

关于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中文网2806 days ago626

reply all(2)I'll reply

  • 巴扎黑

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

    StringIndexOutOfBoundsException inherits RuntimeException and does not need to be explicitly processed.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:51:21

    The first exception thrown is a checked exception, which is a compiler exception, so it must be handled manually. The second thrown StringIndexOutOfBoundsException is an unchecked exception and a runtime exception, so there is no need to handle it manually

    reply
    0
  • Cancelreply