Java custom catching exception

Insert image description here

demand analysis

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

Now, there is such a method to get a data set. I want to get the data in it, but I am worried that the list will be empty. The method requires that the return is an id and cannot be a prompt. How should I solve it?

problem solved

If you want to elsehandle the situation when the obtained data is empty in the branch , electricalCustomerlistyou can throw a custom exception and capture and process it where this method is called. Here are some things to consider:nullelectricalCustomerVO

the first method

  1. Define a custom exception class, for example:
public class ElectricalCustomerNotFoundException extends RuntimeException {
    
    
    public ElectricalCustomerNotFoundException(String message) {
    
    
        super(message);
    }
}
  1. elseThis exception is thrown in the branch :
}else {
    
    
    throw new ElectricalCustomerNotFoundException("Electrical customer not found");
}

Second way

  1. Where the method is called DirectInsertChatRecordsLog, use try-catcha block to catch the exception and handle it:
try {
    
    
      electricalCustomerVO = electricalCustomerMapper.selectElectricalCustomerList(electricalCustomerVO).get(0);
    // 成功处理的逻辑
} catch (ElectricalCustomerNotFoundException ex) {
    
    
    // 处理 ElectricalCustomerNotFoundException 异常,例如打印日志或返回错误信息给前端
     ex.printStackTrace();
}

In this way, when electricalCustomerVOis empty, ElectricalCustomerNotFoundExceptionan exception will be thrown, and then you can catch this exception in the upper logic and handle it accordingly. This helps provide clearer error messages and better code maintainability.

Guess you like

Origin blog.csdn.net/weixin_53742691/article/details/132591417