【问题标题】:Exception handling continue on error and then rethrow异常处理继续出错,然后重新抛出
【发布时间】:2011-09-27 23:23:30
【问题描述】:
     //Assume list1 and list2 are populated with states as 2
    foo (List<Class1> list1, List <Class1> list2) {

         boolean error = false;
          try {
             operate on list1
         } catch (Exception e) {
              error = true;
             //Modify list1 objects to state 1
        }

          try {
             operate on list2
         } catch (Exception e) {
              error = true;
             //Modify list2 objects to state 1
         }

        //What are the problems and what is the best practice for this
         if (error)
             throw new Exception(…);  //How should i really rethrow the exception

    }

【问题讨论】:

  • 这样的设计合理吗?如果第一个操作已经发生错误并且您只会抛出异常,那么对 list2 进行操作有什么意义?为什么不马上扔掉?

标签: java exception-handling


【解决方案1】:

我要做的主要改进是存储所有发生的异常,并以某种方式在某处使它们可用。否则,它似乎很好。

对于持怀疑态度的人来说,即使发生异常也想要完成一些工作并不是真正的异常。批处理是一个非常典型的案例。

【讨论】:

    【解决方案2】:

    除了正确设置 throws 子句等之外,它在技术上没有任何问题。您甚至可以保存捕获的异常之一并重新抛出它。

    不清楚你为什么要这样做,但我做得更奇怪。

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 2021-05-13
      • 2010-09-13
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多