我正在寻找有关如何在以下场景中处理 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.
}
所以这里的问题是如何将 map 数据添加到抛出的异常中?基本上我需要将异常列表发送到调用方法,作为异常处理的一部分。 我们有办法做到这一点吗? 如果答案是众所周知的,那么这可能是一个非常愚蠢的问题,但我在任何地方都找不到确切的答案。
最佳答案
为什么不直接构建一个 List<Exception>
当你迭代时?然后完成后抛出 CustomException
(源自 Exception
)如果该列表不为空,并提供 List<Exception>
作为 CustomException
中的一个字段.
您可能不想存储 List<Exception>
但是一个List<Info>
哪里Info
表示导致异常的数据。这可能会更轻量。
更好的是,创建一个 ErrorCollator
您可以添加的对象 Exceptions
当它们发生时。完成后,请调用 ErrorCollator.throwExceptionIfReqd()
,并且该对象本身可以确定是否抛出异常(简单来说,如果 List
不为空)。这样您就拥有了可以一致使用的可重用组件/模式。即使不立即行动,也许值得努力。
关于Java 自定义异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12835119/