1.当JDK提供的标准异常类无法充分表达我们要求时,可以自定义异常类.
2.自定义的异常类需继承Exception或Exception的子类.
3.自定义异常类如果继承Exception类,则为受检查异常,需要对其进行处理;若不想处理,可以继承运行时异常RuntimeException类.
自定义异常类
class IllegalAgeExecption extends RuntimeException{
public IllegalAgeExecption() {
}
public IllegalAgeExecption(String msg) {
super(msg);
}
}
自定义异常类的使用
public static void main(String[] args) {
person p1=new person();
p1.setAge(-1);
}
class person{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<0) {
try {
throw new IllegalAgeExecption("年龄不能为负数!");
}catch(IllegalAgeExecption e) {
e.printStackTrace();
}
}else {
this.age=age;
}
}
}
class IllegalAgeExecption extends RuntimeException{
public IllegalAgeExecption() {
}
public IllegalAgeExecption(String msg) {
super(msg);
}
}
效果