0
点赞
收藏
分享

微信扫一扫

Java自定义异常类型

认真的老去 2022-03-12 阅读 156
package 异常;

/**
 * @Author Jin XueYang
 * @Date 2022/3/10
 */
public class Student {
    private int age;
    private String name;
    private String sex;

    public int getAge() {
        return age;
    }

    public void setAge(int age) throws MyExceptionAgeBig,MyExceptionAgeSmall {
        if(age>80){
            throw new MyExceptionAgeBig("年龄太大,重录");
        }else if(age<1){
            throw new MyExceptionAgeSmall("年龄太小,重录");
        }
            this.age=age;


    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public static void main(String[] args) throws MyExceptionAgeBig, MyExceptionAgeSmall {
        Student student = new Student();
        try {
            student.setAge(0);
        } catch (MyExceptionAgeBig myExceptionAgeBig) {
            myExceptionAgeBig.printStackTrace();
            student.setAge(90);
        } catch (MyExceptionAgeSmall myExceptionAgeSmall) {
            myExceptionAgeSmall.printStackTrace();
            student.setAge(12);
        }
        System.out.println(student.getAge());


    }

}

class MyExceptionAgeBig extends Exception{
    public MyExceptionAgeBig(String message){
        super(message);
    }
}

class MyExceptionAgeSmall extends Exception{
    public MyExceptionAgeSmall(String message){
        super(message);
    }
}
举报

相关推荐

0 条评论