//AgeRangeException.java public class AgeRangeException extends RuntimeException { public AgeRangeException() { }
public AgeRangeException(String message) { super(message); } }
//NameLengthException.java public class NameLengthException extends RuntimeException{ public NameLengthException() { }
public NameLengthException(String message) { super(message); } }
//Student.java public class Student { private String name; private int age;
public Student() { }
public Student(String name, int age) { this.name = name; this.age = age; }
/** * 获取 * @return name */ public String getName() { return name; }
/** * 设置 * @param name */ public void setName(String name) { int length=name.length(); if(length<3 || length>10){ throw new NameLengthException("姓名长度为"+length+",不符合范围"); }
this.name = name; }
/** * 获取 * @return age */ public int getAge() { return age; }
/** * 设置 * @param age */ public void setAge(int age) { if(age<18||age>40){ throw new AgeRangeException("年龄为"+age+",不符合范围"); } this.age = age; }
public String toString() { return "Student{name = " + name + ", age = " + age + "}"; } }
/* 请输入学生姓名:aa NameLengthException: 姓名长度为2,不符合范围 at Student.setName(Student.java:28) at Test.main(Test.java:11) 请输入学生姓名:aaaaaaaaaaaaaaaa NameLengthException: 姓名长度为16,不符合范围 at Student.setName(Student.java:28) at Test.main(Test.java:11) 请输入学生姓名:zhangsan 请输入学生年龄:8 AgeRangeException: 年龄为8,不符合范围 at Student.setAge(Student.java:48) at Test.main(Test.java:15) 请输入学生姓名:zhangsan 请输入学生年龄:50 AgeRangeException: 年龄为50,不符合范围 at Student.setAge(Student.java:48) at Test.main(Test.java:15) 请输入学生姓名:zhangsan 请输入学生年龄:aaa java.lang.NumberFormatException: For input string: "aaa" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at Test.main(Test.java:14) 请输入学生姓名:zhangsan 请输入学生年龄:20 Student{name = zhangsan, age = 20} */