public class AgeOutofBoundsException extends Exception{
private static final long serialVersionUID = 8299254917638606334L;
public AgeOutofBoundsException(){
super("年龄超出范围");
}
public AgeOutofBoundsException(String message) {
super(message);
}
}
public class People {
private int age;
public People( int age,) throws AgeOutofBoundsException {
if(age<1 || age>200)
{
throw new AgeOutofBoundsException();
}
this.age = age;
}
public void setAge(int age) throws AgeOutofBoundsException {
if(age<1 || age>200)
{
throw new AgeOutofBoundsException("年龄不在1--200之间:"+age);
}
this.age = age;
}
public int getAge() {
return age;
}
}
本文介绍了一个简单的Java程序,用于创建一个People类,并在实例化对象或设置年龄属性时检查年龄的有效性。如果年龄超出合理范围(1-200岁),则会抛出自定义异常AgeOutofBoundsException。
1220

被折叠的 条评论
为什么被折叠?



