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 异常,然后你可以在上层逻辑中捕获此异常并进行相应的处理。这有助于提供更清晰的错误信息和更好的代码可维护性。

猜你喜欢

转载自blog.csdn.net/weixin_53742691/article/details/132591417