Java开发编码异常习惯处理

1.错误的捕获方式
在捕获了异常之后什么都不做,相当于忽略了这个异常。千万不要使用空的catch块,空的catch块意味着你在程序中隐藏了错误和异常,并且很可能导致程序出现不可控的执行结果。如果你非常肯定捕获到的异常不会以任何方式对程序造成影响,最好用Log日志将该异常进行记录,以便日后方便更新和维护.

(1)
这里写图片描述

你的代码中最好不要出现这类的异常代码,真出现异常了,异常信息打印根本不会出现在日志文件里
(2)
这里写图片描述

这种异常打印也是很智障的,虽然最终异常信息被打印了,但是却没有详细的异常信息记录

2.正常的打印方法

这里写图片描述

3.当你想要想要在发生异常时,终止程序继续运行下去,可以写好的业务异常类继承RuntimeException


public class BusinessException extends RuntimeException {
        static final long serialVersionUID = -7134897190745766939L;
        public BusinessException() {
            super();
        }
        public BusinessException(String message) {
                super(message);
        }

        public BusinessException(String message, Throwable cause) {
            super(message, cause);
            System.out.println("发生运行异常··");
        }

        public BusinessException(Throwable cause) {
            super(cause);
        }
}

测试类:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestException {

     private static final Logger log = LoggerFactory.getLogger(TestException.class);

    public static final Integer TYPE1 = 1;
    public static final Integer TYPE2 = 2;
    public static final Integer TYPE3 = 3;

    public static final String MESSAGE1 = "开发人员调试";
    public static final String MESSAGE2 = "反馈给调用者";
    public static final String MESSAGE3= "反馈操作者";

    public static void main(String[] args) {

        try {
            System.out.println(9/0);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new BusinessException(MESSAGE1, e);
        }finally{
            System.out.println("finally");
        }
        System.out.println("outside----------");
    }

}

运行结果:
这里写图片描述

可以看出:System.out.println(“outside———-“);并没有往下执行

当你使用前端界面调用,遇到异常,有做业务类抛出异常时,前端将会给出异常错误提醒:
这里写图片描述

4.业务异常处理类,正确捕获异常

 try {
            response = merAccountService.selectByAcctcode(request, pageable);

            // 返回成功报文
            MessageUtil.createCommMsg(response);

        } catch (BizException e) {
            log.error(Constants.BUSINESS_ERROR, e);
            // 组织错误报文
            MessageUtil.errRetrunInAction(response, e);
        } catch (Exception ex) {
            log.error(Constants.EXCEPTION_ERROR, ex);
            // 组织错误报文
            MessageUtil.createErrorMsg(response,ex);
        }
        log.info(Constants.REPONSE_MSG, JSON.toJSONString(response));
        return response;
    }

注意不要遗漏捕获Exception非运行期异常,这点很重要。有人在这里可能会问,业务异常不是继承了Exception了嘛,为什么不直接只捕获一个Exception呢,其实这里主要是作为一个区分,项目中,我们可把控的基本都是业务异常,那种不可把控的自然是Exception,我们也可以称做系统异常,项目是不能预知它的出现的,所以统一归为一类,并且code也唯一

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值