java中如何创建自定义异常Create Custom Exception

9.创建自定义异常 Create Custom Exception  

马克-to-win:我们可以创建自己的异常:checked或unchecked异常都可以, 规则如前面我们所介绍,反正如果是checked异常,则必须或者throws,或者catch。到底哪个好,各路架构师大神的意见是50对50。见我本章后面的附录。sun公司开始说,checked异常可以使你的系统异常语义表达很清楚。但很多人经过一段时间的实践后,马上表示了异议。checked异常是java独有的,但连Thinking in java的作者都表示,checked异常作为一种java特有的实验行为,不是很成功。我个人的意见是:为了达到解耦的目的,最好继承unchecked异常。否则你各种业务方法都得throws。将来业务方法一旦改变,还得考虑处理这些throws。(新手可忽略)比如你的业务方法a里如果新加了一句throw受检异常,而且你还没有catch,则调用你这个a方法的客户程序将必须或者catch或者throws,反正必须做出相应调整。如果当初你的a方法里只是抛出一个非受检异常,客户程序就不用做任何调整了。

例1.9.1

public class Test {
    public static void main(String args[]) throws RelationshipExceptionMark_to_win {
        int talkTimesPerDay = 2;
        if (talkTimesPerDay < 3) {
            RelationshipExceptionMark_to_win e = new RelationshipExceptionMark_to_win();
            e.setMsg("每天说话小于3 次,抛出关系异常的异常,分手");
            System.out.println("马克-to-win:here");
            throw e;
        }
        System.out.println("马克-to-win:优雅结束");
    }
}
class RelationshipExceptionMark_to_win extends Exception {
    String msg;
    String getMsg() {
        return msg;
    }
    void setMsg(String msg) {
        this.msg = msg;
    }
}

 

例1.9.2

public class Test {
    public static void main(String args[]) {
        int talkTimesPerDay = 2;
        if (talkTimesPerDay < 3) {
            RelationshipExceptionMark_to_win e = new RelationshipExceptionMark_to_win();
            e.setMsg("每天说话小于3 次,抛出关系异常的异常,分手");
            throw e;
        }
        System.out.println("马克-to-win:优雅结束");
    }
}
class RelationshipExceptionMark_to_win extends RuntimeException {
    String msg;
    String getMsg() {
        return msg;
    }
    void setMsg(String msg) {
        this.msg = msg;
    }
}

更多请见:https://blog.csdn.net/qq_44639795/article/details/103108457

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值