自定义异常类AgeException,继承RuntimeException类,包含一个有参构造方法,初始化异常信息;然后定义员工类Employee,包括私有成员变量age(年龄)和设置age的方法setAge(),在方法中判断传入的参数是否符合要求(22 < age < 65),如果符合,则赋给age,否则使用throw抛出异常,并设置异常信息;最后在公共类EmployeeManage的main()方法中创建Employee对象,调用setAge()方法,并使用try-catch-finally语句捕获异常和输出异常信息。
public class AgeException extends RuntimeException {
public AgeException(String errorMessage) {
super(errorMessage);
}
}
public class Employee {
private int age;
public void setAge(int age) {
if (age > 22 && age < 65) {
this.age = age;
} else {
throw new AgeException("错误");
}
}
public int getAge() {
return this.age;
}
}
public class EmployeeManage {
public static void main(String[] args) {
Employee employee = new Employee();
try {
employee.setAge(23);
}catch (AgeException e){
e.printStackTrace();
}finally {
System.out.println(employee.getAge());
}
}
}