学到异常处理了,于是想记录下Java异常处理的细节,以增加对异常处理的印象。
Java常见的异常类之间的继承关系:
(仿李刚老师的《疯狂Java讲义》异常章节的图)
Java的异常被分为两大类:Checked异常(编译时出现异常)和Runtime(运行时异常)。
1、编译时被检测的异常,除了特殊子类RuntimeException体系的,只要是Exception和其子类都是。
这种问题一旦出现,希望在编译时就进行检测,让这种问题有对应的处理方式。
2、编译时不检测异常(运行时异常),就是Exception中的RuntimeException和其子类,这种问题的发生,让 功能无法继续,运算也无法进行,更多是因为调用的原因导致的。或者引发程序内部状态改变,导致异 常。这种问题一般不处理,直接编译通过,在运行时,调用者调用时引发异常从而程序强制停止,此时调用者即可对异常进行修正。
异常Demo演示:
增加一个自定义的异常处理类:
"未报告的异常,必须被捕获或者声明",此处编译不能通过,对于自定义的异常类属于编译时异常,需要在函数在函数出进行声明,代码改成如下:
为什么还是不能编译通过呢?一开始在change()方法体内遇到throw new MyException("You should pass a integer string."); 准备抛出异常,可是change()方法没有显示声明这个异常,对于编译性的异常,需要显示进行声明,让JVM知道后续程序运行时该怎么处理。后来在change()方法声明了我的自定义异常:public void change(String str) throws MyException,所以change()方法中的MyException异常被抛到调用change()方法的main主函数中,所以出现了上面的错误,因而也需要在main主函数声明MyException。下面是正确代码:
编译、运行上面的代码后,最终的MyException异常被抛给JVM,JVM打印出异常跟踪栈。对于这样的异常,可以进行必要的try catch操作。如:
再对比一个编译时异常的例子:
也会出现:
Second.java:14: error: unreported exception IOException; must be caught or declared to be thrown
throw new IOException();
^
1 error
IOException是编译时异常,这样的错误, 所以你还是得在方法体上声明IOException,对于RuntimeException是不需要声明的。See next:
这样就不会在编译时出现情况了,这算是应该注意的一个小细节吧。
下面再来看一个RuntimeException不需要声明的例子:
参考博客:
http://www.blogjava.net/fancydeepin/archive/2015/10/15/382508.html