关于Java异常的疑问
PHP中文网
PHP中文网 2017-04-18 10:49:21
0
2
548

众所周知下面的代码编译不过:

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中文网

认证0级讲师

reply all(2)
巴扎黑

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

左手右手慢动作

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!