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程序,用于验证用户输入的年龄是否在1到200岁之间。如果年龄超出范围,将抛出一个自定义异常AgeOutofBoundsException。
1220

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



