首页 > 代码库 > 自定义异常

自定义异常

1. 编写类,该类继承Exception

public class MyException extends Exception{
    private static final long serialVersionUID = -9146349104405752896L;
    
    public MyException(){
        super();
    }
    
    public MyException(String message){
        super(message);
    }
    
}

2. 编写测试类:

public class TestException {
    
    public static void getAge(int i) throws MyException{
        if(i > 10){
            throw new MyException("不能大于10");
        }
    }
    
    public static void main(String[] args) {
        try {
            getAge(11);
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}

3. 返回结果为:

技术分享

 

自定义异常