自定义异常

自定义异常

  • 使用Java内置的异常类可以描述在变成时出现的大部分异常情况。除此之外, 用户还可以自定义异常。用户自定义异常类, 只需继承Exception类即可。
  • 在程序中使用自定义异常类, 大体可分为以下几个步骤:
  1. 在创建自定义异常类。
  2. 在方法中通过throw关键字抛出异常对象。
  3. 如果当前抛出异常的方法中处理异常, 可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常, 继续进行下一步操作。
  4. 在出现异常方法的调用者中并捕获并处理异常。
public class Application{
	public static void main(String[] args) {
	        try {
	            test(1);
	        } catch (TestException e) {
	            System.out.println("MyException=>"+e);
	        }
	}

    static void test(int a) throws TestException {
        System.out.println("start");
        if (a > 10) {
            throw new TestException(a);
        }
        System.out.println("end");
    }
}

class TestException extends Exception {
    private int detail;

    public TestException(int detail) {
        this.detail = detail;
    }

    @Override
    public String toString() {
        return "TestException{" +
                "detail=" + detail +
                '}';
    }
}

实际应用中的经验总结

  • 处理运行时异常时, 采用逻辑去合理规避同时辅助try-catch处理
  • 在多重catch块后面, 可以加一个catch(Exception)来处理可能会被遗漏的异常
  • 对于不确定的代码, 也可以加上try-catch, 处理潜在的异常
  • 尽量去处理异常, 切忌只是简单地调用printStackTrace()去打印输出
  • 具体如何处理异常, 要根据不同的业务需求和异常类型去决定
  • 尽量添加finally语句去释放占用的资源
/**
 * 自定义异常
 *
 * @author taojun
 * @email 1609591835@qq.com
 * @date 2020年07月24日
 */
public class CUSTOMIZEException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private String msg;
    private int code = 500;

    public CUSTOMIZEException (String msg) {
        super(msg);
        this.msg = msg;
    }

    public CUSTOMIZEException (String msg, Throwable e) {
        super(msg, e);
        this.msg = msg;
    }

    public CUSTOMIZEException (String msg, int code) {
        super(msg);
        this.msg = msg;
        this.code = code;
    }

    public CUSTOMIZEException (String msg, int code, Throwable e) {
        super(msg, e);
        this.msg = msg;
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值