| Java-用户自定义异常1.如何自定义异常继承现有的异常父类:RuntimeException、Exception提供全局常量:serialVersionUID提供重载的构造器
 2.code举例定义:
 package p8exception.p9;
public class MyException extends RuntimeException{
    static final long serialVersionUID = -7023444L;
    public MyException() {
    }
    public MyException(String message) {
        super(message);
    }
    
}
 使用:
 package p8exception.p9;
public class StudentTest {
    public static void main(String[] args) {
        Student s = new Student();
        try {
            s.regist(-1001);
            System.out.println(s);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
class Student {
    private  int id;
    public void regist(int id){
        if(id > 0) {
            this.id = id;
        }else {
            throw new MyException("输入非法");
        }
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                '}';
    }
}
 |