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

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

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级讲师

全部回复(2)
巴扎黑

StringIndexOutOfBoundsException继承了RuntimeException,不需要显式地声明处理。

左手右手慢动作

第一个抛出的是Exception是checked异常,也就是编译器异常,所以必须手动处理。第二个抛出的StringIndexOutOfBoundsException是unchecked异常,运行时异常,所以不需要手动处理

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!