自定义一个学生类,属性有 姓名 年龄,如果用户在给学生年龄赋值时,年龄小于0抛出一个AgeLT0Exception,大于150 抛出一个AgeGT150Exception
1.写Test类
Class Test
:
public static void main(String[] args) throws AgeGT150Exception, AgeLT0Exception {
Student s = new Student();
s.setAge(50);
System.out.println(s.toString());
}
2.写AgeGT150Exception类继承Exception (大于150)
Class AgeGT150Exception
:
public class AgeGT150Exception extends Exception{
public AgeGT150Exception() {
super();
// TODO Auto-generated constructor stub
}
public AgeGT150Exception(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
3.写 AgeLT0Exception类继承Exception(小于0)
Class AgeLT0Exceptionn
:
public class AgeLT0Exception extends Exception{
public AgeLT0Exception() {
super();
// TODO Auto-generated constructor stub
}
public AgeLT0Exception(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
4.写Student类
Class Student
:
public class Student {
String name = "艾力";
int age;
public int getAge() {
return age;
}
public void setAge(int age) throws AgeGT150Exception, AgeLT0Exception {
if(age>150) {
throw new AgeGT150Exception("年龄超过150!");
}
if(age<0) {
throw new AgeLT0Exception("年龄小于0!");
}
this.age = age;
}
@Override
public String toString() {
return "Student [姓名=" + name + ", 年龄=" + age + "]";
}
}
age赋值50时输出的结果:
Student [姓名=艾力, 年龄=50]
age赋值200时输出的结果:
Exception in thread "main" Day17HomeWork.AgeGT150Exception: 年龄超过150!
at Day17HomeWork.Student.setAge(Student.java:11)
at Day17HomeWork.Test.main(Test.java:6)
age赋值-50时输出的结果:
Exception in thread "main" Day17HomeWork.AgeLT0Exception: 年龄小于0!
at Day17HomeWork.Student.setAge(Student.java:14)
at Day17HomeWork.Test.main(Test.java:6)