前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java中如何创建自定义异常Create Custom Exception

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

作者头像
马克java社区
修改2021-04-07 11:37:30
7310
修改2021-04-07 11:37:30
举报
文章被收录于专栏:java大数据

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

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档