29.自定义异常

自定义异常

public class MyException extends Exception{ //继承

    //传递数 >10抛出异常

    private int detail;

    public MyException(int a){

        this.detail = a;

    }

    //alt + insert -> toString:异常的打印信息
    @Override
    public String toString() { //重写方法
        return "MyException{" + detail + '}';
    }
}
public class Test {

    //可能会存在异常的方法
    static void test(int a) throws MyException {

        System.out.println("传递的参数为" + a);

        if(a > 10){
            throw new MyException(a);
        }

        System.out.println("ok");
    }

    public static void main(String[] args) {

        try {
            test(11);
        } catch (MyException e) {
            System.out.println("MyException ->" + e);
        }

    }
}
posted on   小黑确实不黑  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示