图片来自网络
异常类体系


Error
一般指虚拟机相关错误,是程序无法处理的,如OutOfMemoryError、ThreadDeath、系统崩溃等。这种错误由JVM来处理,不可能捕获也无法恢复,JVM在大多数情况下会选择终止线程导致程序中断。
Exception
程序可以捕获处理的异常。分为两种:CheckedException,UncheckedException(RuntimeException及其子类)。
- CheckException发生在编译阶段,必须要使用try…catch(或者throws)否则编译不通过。
- UncheckedException发生在运行期,具有不确定性。
使用try-catch-finally
机制:
1、运行发生异常:系统生成异常对象
2、若异常对象在try块中生成,判断该异常对象是否为catch块形参(xxxException)异常类或其子类的实例,
(1)如果是,JAVA调用该catch块处理该异常对象;(2)否则,把该异常对象与下一个catch块的形参(xxxException)进行比较...

(父类异常catch块应排当在子类异常catch块后面) (try中的局部变量是代码块内部变量,不能在catch块中访问)
3、当程序进入负责处理异常的catch块时,系统生成的异常对象会传入catch块的形参,从而允许catch块通过该对象获得详细的异常信息。从异常对象获取常用异常信息方法:

4、finally:显示回收资源(数据库连接、网络连接、磁盘文件等)


- 退出JVM:
- if you call System.exit() or
- if the JVM crashes first
- try块、catch块中遇到return、throw语句:


自行抛出异常
使用throws声明异常

某一级处理:显示try-catch捕获异常进行处理 / 在方法声明后使用throws声明异常交给上一级调用者处理
使用throw自行抛出异常




catch与throw同时使用
程序只对异常进行部分处理, 还有些处理需要在该方法的调用者中处理

异常链
把原始异常信息隐藏起来,仅向上传递必要的异常提示信息,可以保证底层的异常不会扩散到表现层,可以避免暴露太多的实现细节(封装原则、责任链模式)
在JDK1.4以后,所有Throwable子类在构造器中可以接受一个cause对象(原始异常)作为参数,这样就可以把原始异常传给新的异常,也可以通过这个异常链追踪到异常最初发生的位置


JAVA异常对象栈
printStackTrace()


自定义异常


异常处理规则
- 异常处理机制只能用于处理不可预知的异常(将其与业务代码分离开),不能用来代替正常的流程控制
- 一般尽量避免catch all语句(导致无法对不同异常区分处理)
- 不要忽略捕获到的异常
参考:《疯狂JAVA讲义》