Java中的自定义异常

话不多说,直接上代码:
自定义年龄异常类,继承Exception,并在构造方法中使用super()方法调用父类的构造方法。

public class AgeException extends Exception {
    private int age;

    public AgeException(int age,String msg) {
        super(msg);
        this.age = age;
    }

    @Override
    public String toString() {
        return super.toString();
    }

}

检查年龄中抛出自定义异常:

void checkedAge() throws AgeException{
        if(age<0){
            throw new AgeException(age, "年龄不能小于零");
        }
    }

编写测试类测试:

public class Test {

    public static void main(String[] args) {
        Student student=new Student(-1);
        try {
            student.checkedAge();
        } catch (AgeException e) {
            e.printStackTrace();
        }
    }

}

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/isduxd/article/details/76881681