public class Test05 {
public static void main(String[] args) {
Person p = new Person();
p.setAge(-2);
}
}
class Person{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<0) {
throw new IllegelAgeException("年龄不能为负数"); //抛出异常 throw
}
this.age = age;
}
}
//自定义异常继承runtimeexception
class IllegelAgeException extends RuntimeException{ //Exception就是编译器异常啦
public IllegelAgeException(){
}
public IllegelAgeException(String msg) {
super(msg);
}
}
Java——自定义异常
最新推荐文章于 2024-09-16 20:08:29 发布