java中自定义异常

java中自定义异常,第1张

1、介绍

例子

自己定义的异常

package com.oop.demo8;

public class MyException extends Exception{
    private int detail;

    public MyException(int a) {
        this.detail= a;
    }
    @Override
    public String toString() {
        return "MyException{" +
                "a=" + detail +
                '}';
    }
}

测试

package com.oop.demo8;

public class Test {
    static void test(int a) throws MyException {
        if (a > 10) {
            System.out.println(a);
            throw new MyException(a);
        }
        System.out.println("OK");

    }

    public static void main(String[] args) {
        try {
            Test.test(11);
        } catch (MyException e) {
            System.out.println("MyException is"+e);
        }
    }
}

输出

11
MyException isMyException{a=11}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/923000.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存