定义一个Person类,包含name与age两个成员变量;
在person类的有参构造方法中,进行年龄范围的判断,若年龄为负或大于150岁,则抛出NoAgeException异常,异常提示信息“年龄数值非法”;
要求:在测试类中,调用有参的构造方法,完成Person对象创建,并进行异常处理;
public class Test {
public static void main(String[] args){
Person person=null;
try {
person =new Person("张三",160);
}catch (NoAgeException e){
e.printStackTrace();
}
System.out.println(person.name+":"+person.age);
}
}
//创建异常类
class NoAgeException extends Exception{
public NoAgeException() {
}
public NoAgeException(String message) {
super(message);
}
}
//创建Person类
class Person{
String name;
int age;
public Person() {
}
public Person(String name, int age) throws NoAgeException//声明可能抛出异常{
if (age>150||age<0)
{
throw new NoAgeException("年龄数值非法”);//抛出一个NoAgeException异常对象
}else {
this.name = name;
this.age = age;
}
}
}