软件构造6.2
- Error and Exception in Java
- Exception Handling
- What is Exception?
- Classification of exceptions分类
- Checked and unchecked exceptions
- Declaring Checked Exceptions by throws
- How to Throw an Exception
- Creating Exception Classes
- Catching Exceptions
- Rethrowing and Chaining Exceptions再抛出异常与链接异常
- finally Clause
- The Try-with-Resources (TWR) Statement
- Analyzing Stack Trace Elements
Error and Exception in Java
- error 无能为力,优雅的结束
用户输入错误,设备错误,物理限制 - exception 程序自己导致的问题,可以捕获,可以处理
Exception Handling
What is Exception?
程序执行中非正常的事件,程序无法按照预想的流程执行,将错误信息传递给上层调用者,并报告案发信息,return之外的第二种退出途径
Classification of exceptions分类
- 运行时异常
程序员在代码里处理不当造成 - 其他异常
外部原因
Checked and unchecked exceptions
- checked
从Exception派生出子类
异常发生时,自己catch和处理异常或者告诉编译器不能处理,然后声明您的方法抛出这个异常,编译器会检查是否抛出或者处理了异常
必须捕获并指定错误处理器handler,否则编译无法通过- throws 声明可能会发生某某异常
- throw 抛出某某异常
- try catch finally 捕获并处理某种异常
- unchecked
从Runtimeexception派生出子类
errors runtime exception
可以不处理,编译没问题,但执行时出现就导致程序失败,代表程序中的潜在bug- ArrayIndexOutOfBoundsException
指针越界 - NullPointerException
空指针调用 - NumberFormatException
尝试将字符串转换为数字类型,但字符串没有适当的格式时 - ClassCastException
强转对象失败 - IllegalArgumentException
参数不合法 - IllegalStateException
状态不合适 - NoClassDefFoundError
找不到类
- ArrayIndexOutOfBoundsException
- 如果客户端能通过其他方法修复,则checked,否则unchecked
Declaring Checked Exceptions by throws
包括:调用其他函数传来的异常,自己产生的异常
子类型override父类型中的函数,则子类型抛出的异常不能比夫父类型更宽泛,
子类型可以抛出更具体的,也可以不抛出,
父类未抛出,子类不抛出
How to Throw an Exception
Creating Exception Classes
从Exception或者其子类派生
Catching Exceptions
如果甩锅,就必须声明throws 可能会出现异常
Rethrowing and Chaining Exceptions再抛出异常与链接异常
catch里面也可以抛出异常,这样做的目的是更改Exception的类型,更方便client获取错误信息并处理
finally Clause
异常抛出,正常执行的代码被终止,为抛出异常前的申请资源,需要被清理。
无论是否捕获到异常,finally中的都会执行
The Try-with-Resources (TWR) Statement
Analyzing Stack Trace Elements
通过调用Throwable类的printStackTrace方法来访问堆栈跟踪的文本描述。
一种更灵活的方法是getStackTrace方法,它生成StackTraceElement对象的数组,您可以在程序中分析这些对象