如何将foreach循环内的CustomStatusException抛出到ProductServiceClass
解决方案
核心问题原因
无法传递自定义异常的核心是Product类的catch块没有正确捕获并重新抛出CustomStatusException,同时原代码存在多处语法、逻辑错误需要同步修正。
关键调整点
- 确保自定义异常
CustomStatusException继承自RuntimeException(非受检异常)或Exception(受检异常),如果是受检异常需要在各层调用方法的throws声明中明确声明 - Product类的循环catch块不要吞异常,捕获到目标自定义异常后直接向上抛出
- 修正原代码中返回值错误、变量定义错误等语法问题
调整后完整代码
import java.util.ArrayList; import java.util.List; // 首先确保自定义异常继承关系正确,这里以继承RuntimeException为例 class CustomStatusException extends RuntimeException { private String error; public String getError() { return error; } public void setError(String error) { this.error = error; } } class ProductServiceClass { public void handleProductBusiness() { // 这里模拟jsonresponse对象 JsonResponse jsonresponse = new JsonResponse(); try { new Product().callCustbusinessLogic(); } catch (CustomStatusException cse) { jsonresponse.setError(cse.getError()); } } } class Product { // 方法声明抛出CustomStatusException public List<Customer> callCustbusinessLogic() throws CustomStatusException { List<Customer> validCustomerList = new ArrayList<>(); // 这里假设customerList是已定义的待遍历客户列表 for (Customer customer : customerList) { try { validCustomerList.add(new CustomerCheck().businessLogic()); } catch (CustomStatusException cse) { // 直接捕获到自定义异常后重新抛出,不需要转成标准RuntimeException throw cse; // 如果你需要收集所有客户的异常,不遇到第一个就终止,可以用如下逻辑: // errorList.add(cse); } catch (Exception e) { // 其他非目标异常可以按原有逻辑处理 throw new RuntimeException("业务处理异常", e); } } return validCustomerList; } } class CustomerCheck { public Customer businessLogic() throws CustomStatusException { try { // 原有业务逻辑 Customer customer = new Customer(); return customer; } catch (Exception e) { CustomStatusException cse = new CustomStatusException(); cse.setError("Not a valid customer"); throw cse; } } } // 辅助类,仅做示例 class Customer {} class JsonResponse { private String error; public void setError(String error) { this.error = error; } }
可选扩展:批量收集所有客户异常
如果你需要遍历完所有客户,收集所有校验失败的异常信息,而不是遇到第一个异常就终止流程,可以在Product类中定义一个异常列表存储所有捕获的CustomStatusException,遍历结束后如果异常列表不为空,就封装成一个总的自定义异常向上抛出即可。
内容的提问来源于stack exchange,提问作者alexgmu49
相关产品推荐
相关产品推荐

