package demo2;
//自定义年龄异常
public class AgeException extends Throwable{
public AgeException() {
super();
}
public AgeException(String message) {
super(message);
}
}
package demo2;
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if (age>0 && age<120) {
this.age=age;
} else {
throw new AgeException("年龄必须在1-120之间");
}
}
}
package demo2;
public class Test {
public static void main(String[] args) throws AgeException {
// TODO Auto-generated method stub
Student zh=new Student();
zh.setName("张三");
zh.setAge(-12);
}
}