Java 基础(自定义异常)

如何自定义异常类?

  1. 继承于现有的异常结构: RuntimeException, Exception
  2. 提供全局常量: serialVersionUID
  3. 提供重载的构造器

throw 和 throws 区别:
throw 表示抛出一个异常类的对象,生成异常对象的过程。声明在方法体内。
throws 属于异常处理的一种方式,声明在方法的声明处。

MyException.java

package com.klvchen.java2;

public class MyException extends RuntimeException {
    
    static final long serialVersionUID = -7034897190745766999L;
    
    public MyException() {}
    
    public MyException(String msg) {
        super(msg);
    }

}
StudentTest.java

package com.klvchen.java2;

public class StudentTest {
    public static void main(String[] args) {
        Student s = new Student();
        try {
            s.regist(-100);
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
    
}


class Student{
    
    private int id;
    
    public void regist(int id) throws Exception{
        if(id > 0) {
            this.id = id;
        }else {
            throw new MyException("不能输入负数");
        }
    }
    
    public String toString() {
        return "Student [id=" + id + "]";
    }
}

posted @ 2021-11-29 14:15  民宿  阅读(46)  评论(0)    收藏  举报