I am looking for suggestion on how to handle exception in java in a scenario, where
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.
}
So the question here is how can I add the Map data to the exception thrown ? basically I need the list of exceptions to be sent to the calling method, as part of exception handling.
Is there a way we can do this ?
It might be a very silly question if the answer is wellknown but I dint find the exact answer anywhere.
Why not just build a
List<Exception>as you iterate ? Then upon completion throw aCustomException(derived fromException) if that list is not empty, and provide theList<Exception>as a field in thatCustomException.You may prefer not to store a
List<Exception>but aList<Info>whereInforepresents the data resulting in the exception. That would likely be more lightweight.Better still, create an
ErrorCollatorobject that you can addExceptionsto as they occur. Once you’re done, callErrorCollator.throwExceptionIfReqd(), and that object itself can determine whether to throw the exception (simply, if theListis not empty). That way you have a reusable component/pattern that you can use consistently. Perhaps worth working towards, if not doing immediately.