Java自定义异常处理

Swa*_*ika 0 java exception

我正在寻找关于如何在场景中处理java异常的建议,其中

Class A.test() 
{
    ClassB.test1()
}


test1()
{
   Map listOfExceptions = new HashMap();
   for()
   {
      try{
      }
      catch(custException e){
       // I want the for loop to continue even if there is an exception
       //So I am not throughing now rather adding the exception message to map with 
       //the field name for which for loop is running as key and message as value
      {
   }

// at some point if map has >0 records I want to throw an exception to classA.
}
Run Code Online (Sandbox Code Playgroud)

所以这里的问题是如何将Map数据添加到抛出的异常中?基本上我需要发送到调用方法的异常列表,作为异常处理的一部分.有没有办法可以做到这一点?如果答案是众所周知的,那可能是一个非常愚蠢的问题,但我在任何地方都找到了确切的答案.

Bri*_*new 7

为什么不在List<Exception>迭代时构建一个?然后在完成时抛出a CustomException(派生自Exception),如果该列表不为空,并将其List<Exception>作为字段提供CustomException.

您可能不希望存储a List<Exception>而是List<Info>where Info表示导致异常的数据.这可能会更轻巧.

更好的是,创建一个ErrorCollator可以在Exceptions发生时添加的对象.一旦完成,调用ErrorCollator.throwExceptionIfReqd(),该对象本身可以确定是否抛出异常(简单地说,如果List它不是空的).这样,您就拥有了可以一致使用的可重用组件/模式.如果不立即做,也许值得努力.