0

我正在寻找有关如何在一个场景中处理 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.
}

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

4

4 回答 4

7

为什么不只是在迭代时构建一个List<Exception>?然后,如果该列表不为空,则在完成时抛出一个CustomException(派生自),并将 提供为 that 中的字段。ExceptionList<Exception>CustomException

您可能不希望存储 aList<Exception>但 a List<Info>whereInfo表示导致异常的数据。那可能会更轻量级。

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

于 2012-10-11T08:21:35.577 回答
0

创建一个自定义异常类,例如

Class CustomException extends Exception{

Map listOfExceptions; 


CustomException (Map m){
  ListofExceptions=m;
 }
}

现在,当记录 >0 或任何其他条件时抛出此客户异常。

throw new CustomException(listOfExceptions);
于 2012-10-11T08:24:56.217 回答
0

查看以下代码,了解如何将异常添加到 HashMap

public class ClassA {

    HashMap hm = new HashMap(); //HashMap Object that holds Exceptions

    public ClassA(){
        try {
            runA();
        } catch (Exception ex) {
            hm.put("a", ex); //put Exception in HashMap
        }
        try {
            runB();
        } catch (Exception ex) {
            hm.put("b", ex); //put Exception in HashMap
        }
    }

    private void runA() throws Exception {
        throw new Exception("a"); //Generate exception a
    }

    private void runB() throws Exception {
        throw new Exception("b"); //Generate exception b
    }
}

然后你可以通过提供一些getter函数来扩展这个类来获取你的HashMap对象并使用这个循环(迭代器)你可以迭代它:

// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
  Map.Entry me = (Map.Entry)i.next();
  System.out.print(me.getKey() + ": ");
  System.out.println(me.getValue());
} 
于 2012-10-11T08:29:18.053 回答
0

请尝试以下代码。在我的示例代码中,我将 String 解析为 int。

直到数组结束,解析继续。如果发生异常,把它放到地图上。该映射包含作为键运行 for 循环的字段名称和作为值运行的异常消息。

在数组的最后,检查映射是否需要向调用类抛出异常。

public class ExceptionHadlingTest {

    public static void main(String[] args) {
        A1 a1 = new A1();
        a1.test();
    }
}
class A1 {
    public void test() {

        B1 b1= new B1();
        try {
            b1.test1();
        } catch (Exception e) {
        }
    }
}

class B1 {
    public void test1() throws Exception {
        Map<String, String> exceptions = new HashMap<String, String>();
        String[] array = {"1","a","2","b","6"};
        for (int i=0; i< array.length ; i++) {
            try {
                int a = Integer.parseInt(array[i]);
            } catch (Exception e) {
                exceptions.put(array[i], e.getMessage());
            }
        }
        if(exceptions.size() > 0) {
            System.out.println("Total Number of exception " + exceptions.size());
            for (Entry<String, String> entry : exceptions.entrySet()) {
                System.out.println(entry.getKey() + " " + entry.getValue());
            }
            throw new Exception();
        }
    }
    private int parse(String str) {
        int a = Integer.parseInt(str);
        return a;
    }
}

您也可以在 for 中使用 customException。

于 2012-10-11T08:54:34.357 回答