关于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.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异常,运行时异常,所以不需要手动处理
相关文章:
1. javascript - vue组件通过eventBus通信时,报错a.$on is not a function2. python3.x - python3.5.2安装时make报错求助3. html - vue项目中用到了elementUI问题4. javascript - 在使用 vue.js element ui的时候 怎么样保留table翻页后check的值?5. mysql_replication - mysql读写分离时如果单台写库也无法满足性能怎么解决6. ionic 项目 ionic build android -release 打包时报错7. linux - ubuntu 命令行中文 显示菱形,期望通过引入字体解决而不是zhcon这种方式8. angular.js - 如何控制ngrepeat输出的个数9. mac里的docker如何命令行开启呢?10. python - 如何用pandas处理分钟数据变成小时线?

网公网安备