Day26自定义异常

image
image

package Demo2;
//自定义异常类
public class Myexception extends Exception {
    //传递数字>10
    private int detail;

    public Myexception(int a) {
        this.detail = a;
    }
    //重写toString打印异常信息
    @Override
    public String toString() {
        return "Myexception{" +
                "detail=" + detail +
                '}';
    }
}
package Demo2;


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("出现异常");
        }
    }
}
posted @ 2025-10-05 03:04  冰涿  阅读(5)  评论(0)    收藏  举报