一、Java异常体系
- Throwable
- Error
- Exception
- RuntimeException
- 非RuntimeException
Java异常分为运行时异常和编译型异常。
运行时异常只有在程序运行时被发现和处理。
编译型异常在编译阶段就能被发现,并且必须处理。
通常自定义异常都是编译型异常。
二、声明和抛出异常
1 2 3 4
| 方法名() throws 异常类型1,异常类型2{ throw 异常对象 }
|
三、捕获和处理异常
- 调用声明了编译型异常的方法必须进行异常捕获和处理
- 使用try…catch捕获处理异常
- finally语句块中是必须执行的代码
- 或者调用方法声明中继续抛出异常,由上层调用者处理
1 2 3 4 5 6 7 8 9 大专栏 JAVASE学习笔记—009 异常处理s="line">10 11 12 13 14 15 16
| try{ }catch(IOException e){ }catch(Exception e){ }finally{ }
try{
}catch(异常类型1 | 异常类型2 e){
}
|
异常常用的方法
- getMessage() 获取异常信息
- printStack() 打印异常方法调用堆栈
四、自定义异常
- 自定义异常必须直接/间接继承Exception类
- 通常在Java预定义异常不能满足要求时,会自定义异常。