Java自定义捕获异常

在这里插入图片描述

需求分析

ElectricalCustomerVO electricalCustomerVO = new ElectricalCustomerVO();
electricalCustomerVO.setElcNumber(chatRecordsLog.getDeviceNumber());
List<ElectricalCustomerVO> electricalCustomerlist = electricalCustomerMapper.selectElectricalCustomerList(electricalCustomerVO);

现在,有这么一个获取数据集合的方法,我想取里面的数据,但是我担心会列表为空,方法要求返回的是一个id,不能是一个提示,我该怎么解决呢?

问题解决

想要在 else 分支中处理当electricalCustomerlist 获取数据为nullelectricalCustomerVO 为空时的情况,可以抛出一个自定义的异常并在调用此方法的地方进行捕获和处理。以下是可以考虑的做法:

第一种方法

  1. 定义一个自定义异常类,例如:
public class ElectricalCustomerNotFoundException extends RuntimeException {
    public ElectricalCustomerNotFoundException(String message) {
        super(message);
    }
}
  1. else 分支中抛出此异常:
}else {
    throw new ElectricalCustomerNotFoundException("Electrical customer not found");
}

第二种方式

  1. 在调用 DirectInsertChatRecordsLog 方法的地方,使用 try-catch 块捕获异常并进行处理:
try {
      electricalCustomerVO = electricalCustomerMapper.selectElectricalCustomerList(electricalCustomerVO).get(0);
    // 成功处理的逻辑
} catch (ElectricalCustomerNotFoundException ex) {
    // 处理 ElectricalCustomerNotFoundException 异常,例如打印日志或返回错误信息给前端
     ex.printStackTrace();
}

这样,当 electricalCustomerVO 为空时,会抛出 ElectricalCustomerNotFoundException 异常,然后你可以在上层逻辑中捕获此异常并进行相应的处理。这有助于提供更清晰的错误信息和更好的代码可维护性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IT小辉同学

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

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

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

打赏作者

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

抵扣说明:

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

余额充值