1.4异常
文章目录
1.异常架构图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EXmPE3s7-1686273384619)(C:\Users\10059\AppData\Roaming\Typora\typora-user-images\image-20220114142543215.png)]
(1)CheckedException
非运行时异常及其子类。编译器要求必须要处理
(2)UnCheckedException
运行时异常+Error 及他们的子类。可以选择是否处理,如果不处理则默认交给JVM处理(打印错误堆栈信息)
2.异常处理机制
(1)声明异常:throws
当前代码块处理不了,往上一层方法栈抛,直到被处理,如果最终都没有处理则交给JVM处理。
(2)抛出异常:throw
(3)捕获异常:try-catch-finally
①代码
try{
//业务代码
}
catch(Exception e1){
//异常处理
}
finally{
//一些关闭流操作
}
②注意事项
- 如果有多个catch块,在发生异常时catch捕获到一个后就不会再进入其它catch块。因此把父类异常放在上层,子类异常放在下层
- 如果有finally块,对于try和catch中有return、throw的情况
- try和catch中的return,throw语句会先保存等到finally语句块执行完再返回
- try和catch中的return,throw语句返回的数据,如果是基本类型则finally语句中对其变更不起作用,如果是引用类型则可以改变对象内部属性
- finally块有return|throw:会覆盖try或catch里的return|throw
3.自定义异常
public class ApplicationException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7640793404157007568L;
/**
* 错误码
*/
private PaasError error;
/**
* 异常体
*/
private Throwable throwable;
public ApplicationException(PaasError error) {
super(error.getDescription());
this.error = error;
}
public ApplicationException(PaasError error, Throwable throwable) {
super(error.getDescription(), throwable);
this.error = error;
this.throwable = throwable;
}
public PaasError getError() {
return error;
}
public void setError(PaasError error) {
this.error = error;
}
public Throwable getThrowable() {
return throwable;
}
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
}
c void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
}