在 Exception,RuntimeException 中抛出自己定义的异常信息

1.(Exception)自定义异常处理

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.setAge(-1);
    }
}
class Person{
    int age;
    public void setAge(int age){
        try{   
            if(age<0){
                throw new CustomException("年龄不能是负数");
            }
            this.age = age;
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
class CustomException extends Exception{
    public CustomException(String msg){
        super(msg);
    }
}

运行结果:

CustomException: 年龄不能是负数
        at Person.setAge(Main.java:12)
        at Main.main(Main.java:4)

2.(RuntimeException)自定义异常处理

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.setAge(-1);
    }
}
class Person{
    int age;
    public void setAge(int age){
        if(age<0){
            throw new CustomException("年龄不能是负数");
        }
        this.age = age;
    }
}
class CustomException extends RuntimeException{
    public CustomException(String msg){
        super(msg);
    }
}

运行结果:

Exception in thread "main" CustomException: 年龄不能是负数
        at Person.setAge(Main.java:11)
        at Main.main(Main.java:4)

小结:

1.自定义异常必须继承异常类
2.Exception异常必须用 try 和 catch 捕获
3.RuntimeException异常 可以不用 try 和 catch 捕获

文章目录