书上例题 自定义一个Java异常类

class AgeException extends Exception{
 String message;
 AgeException(String name,int m){
  message = name+"的年龄"+m+"不正确";
 }
 public String toString() {
  return message;
 }
}              //1到9行定义异常的子类AgeException
class User{
 private int age = 1;
 private String name;
 User(String name){
  this.name=name;
 }
 public void setAge(int age) throws AgeException{   //定义setAge()方法并且进行异常的声明
  if(age>=50||age<=18)
   throw new AgeException(name,age);
  else              //17到19行在年龄>=50||<=18时,抛出异常
   this.age=age;
 }
 public int getAge() {
  System.out.println("年龄"+age+"输入正确");
  return age;
 }
}
public class Age {
 public static void main(String[] args) {
  User 张三=new User("张三");
  User 李四=new User("李四");
  try {
   张三.setAge(30);
   System.out.println("张三的年龄是:"+张三.getAge());
  }
  catch(AgeException e) {
   System.out.println(e.toString());   //32到38行调用setAge()方法时必须捕获异常
  }
  try {
   李四.setAge(18);
   System.out.println("李四的年龄是:"+李四.getAge());
  }
  catch(AgeException e) {
   System.out.println(e.toString());
  }
 }
}

你可能感兴趣的:(书上例题 自定义一个Java异常类)