Day6 异常
常见异常
Exception
: 用于用户程序可能出现的异常情况,它也是用来创建自定义异常类型类的类。Error
:定义了在通常环境下不希望被程序捕获的异常。一般指的是 JVM 错误,如堆栈溢出。
自定义异常
// 自定义异常Chap1:继承Exception
public class Chap1 extends Exception{
// 自定义异常类中的信息
private Integer code;
// message这个属性来自父类,可以直接使用,不用定义
public Chap1(String message, Integer code) {
super(message);
this.code = code;
}
@Override // 重写输出格式
public String toString() {
return "Chap1{" +
"message=" + super.getMessage() +
"code=" + code +
'}';
}
}
class Test1{
// throws Chap1: 将该异常交给下一级去处理
public static int add(int a, int b) throws Chap1 {
int result = a + b;
if (result < 1){
// 使用自定义的异常抛出,会结束该方法
throw new Chap1("自定义异常", 400);
}
return result;
}
public static void main(String[] args) {
// 前面抛出了异常,这里需要捕获处理
try {
add(-2, 0);
}catch (Chap1 chap1){
chap1.printStackTrace();
}finally {
System.out.println("不管怎样都会执行的语句");
}
}
}
异常捕获(
try-with-resources
)
- 面对必须要关闭的资源,可以多使用
- 任何
catch
或finally
块在声明的资源关闭后再运行
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}