异常简介
1.概念:程序在运行过程中出现的不正常情况
2.分类
3.出现的错误/异常的可能原因
1).错误:
StackOverflowError(栈溢出)
OOM(内存溢出)
2).异常:
空指针
读取不存在的文件
越界
网络问题
异常参数
程序中断
树图
4.引入:为什么要处理异常
5.如何去处理异常
1).直接处理 try catch
a.格式:
b.可能会遇到的一些问题
i.多级catch
ii.异常不匹配
iii.finally(finally,会在try/catch的return执行前执行)
iv.单try
2).throws:继续抛出,交给主调方法处理
a.在继承中,子类重写方法的异常对象一定要小于/等于父类的异常抛出
d.注意异常机制的价值:出现异常,通过异常处理整个程序依然执行,不会停止,但会打印异常信息
e.自定义异常:自定义异常可以 继承 运行时异常 / 编译时异常 (个人需求)
/**
*自定义异常类
*/
public class IDLengthException extends Exception{
public IDLengthException() {
super("THE LENGTH OF ID MUST BE 18 LENGTH");
}
}
/**
*测试自定义异常
* 限制id号为18位
*/
public class Person {
private String id;
private String name;
private int age;
public Person() {
}
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
/**
* 抛出自定义异常
* @param id
* @throws IDLengthException
*/
public void setId(String id) throws IDLengthException {
if (id.length() != 18){
throw new IDLengthException();
}
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class TestException {
public static void main(String[] args) {
Person person = new Person();
try {
//通过异常限制id
person.setId("123456789876543210");
person.setName("屠龙");
person.setAge(18);
System.out.println(person);
} catch (IDLengthException e) {
e.printStackTrace();
}
}
}
3).throw和throws的区别
i. 总结throw 和throws 的区别、
1) thrwos:对执行语句可能出现的异常提前声明预判
2) throw:
a) 对执行语句执行时真正出现异常的解决方法:抛出
b) 一旦方法遇到throw执行结束时,方法结束
c) 比较
i. Break:跳出当前循环
ii. Continue:跳出当前循环,执行下一次循环
iii. Return:结束方法
iv.throw:结束方法
4).异常中数据的获取
finally,会在try/catch的return执行前执行。
5).SE阶段一些常见的异常