自定义异常处理(样例)

来源:互联网 发布:python和php 编辑:程序博客网 时间:2024/06/05 17:34
package Lianxi1219;/** * 自定义一个学生类, * 属性有 姓名 年龄, * 如果用户在给学生年龄赋值时, * 年龄小于0抛出一个AgeLT0Exception, * 大于150 抛出一个AgeGT150Exception */public class Student {    private String name;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) throws AgeLT0Exception, AgeGT150Exception {        if(age<0){            throw new AgeLT0Exception();        }if(age>150){            throw new AgeGT150Exception();        }        this.age = age;    }    @Override    public String toString() {        return toString();    }}
package Lianxi1219;@SuppressWarnings("serial")public class AgeExecption extends Exception {    public AgeExecption() {    }    public AgeExecption(String mess){        super(mess);    }}
package Lianxi1219;public class AgeLT0Exception extends AgeExecption {    /**     *      */    private static final long serialVersionUID = 1L;    public AgeLT0Exception(){        this("年龄不能小于0岁");    }    public AgeLT0Exception(String mess) {        super(mess);    }}
package Lianxi1219;public class AgeGT150Exception extends AgeExecption {    /**     *      */    private static final long serialVersionUID = 1L;    public AgeGT150Exception(){        this("年龄不能大于150岁");    }    public AgeGT150Exception(String mess) {        super(mess);    }}
package Lianxi1219;import java.util.Scanner;public class Stest {    public static void main(String[] args) throws AgeExecption{        Student s=new Student();        Scanner sc=new Scanner (System.in);        System.out.println("请输入学生姓名:");        s.setName(sc.next());        System.out.println("请输入学生年龄:");        s.setAge(sc.nextInt());        sc.close();        if(sc.nextInt()<0){            throw new AgeLT0Exception();        }if(sc.nextInt()>150){            throw new AgeGT150Exception();        }    }}
0 0