【问题标题】:Catch multiple exceptions and throw a new list of exceptions捕获多个异常并抛出一个新的异常列表
【发布时间】:2016-04-30 11:00:05
【问题描述】:

看下面的代码:

public void editProduct(String articleNumber, ...) {
 product.setArticleNumber(articleNumber);
 product.setDescription(description);
 product.setLendable(lendable);
 product.setName(name);
 product.setPrice(price);
 product.setPlace(place);
}


所有的 setter 都可以抛出带有自定义消息的 ProductException。 但我想捕捉所有的异常。如果有异常,我想将所有错误的列表发送到 GUI。

我该怎么做,还是需要用 Try Catch 包围每一行?

【问题讨论】:

  • 如果出现异常,为什么还要继续尝试更改产品?如果出现异常,说明有问题;并且product 应该保持在您开始尝试编辑它之前的状态(Effective Java 将此称为"failure atomicity")。
  • 嗨,我想向用户显示不同的错误:' - 没有描述, - 没有价格 - ...'
  • 这里有什么异常?产品为null?一些方法参数为null?这些方法是简单的setter?这里怎么可能出现异常...
  • 您好,异常如 null、空格或空值、逻辑(名称需要唯一)、...

标签: java exception try-catch catch-block


【解决方案1】:

你可以试试下面的代码。如果合适的话

public void editProduct(String articleNumber, ...) {
    int count=1;
    Vector<String> v=new Vector<String>();
    while(count<=6)
    {
        try{

            switch(count)
            {
                case 1:product.setArticleNumber(articleNumber);break;//assume it will throw ArticalException
                case 2:product.setDescription(description);break;   //DescriptionException
                case 3:product.setLendable(lendable);break;         //LendableException
                case 4:product.setName(name);break;                 //NameException
                case 5:product.setPrice(price);break;               //PriceException
                case 6:product.setPlace(place);break;               //PlaceException
            }
            count++;
        }catch(Exception e)
        {
            v.add(e.getMessage);
            count++;
            /*
             *suppose there is some exception like ArticalException,PriceException
             *then it will store in vector and your program running continue
             *and at last you have the list of all exceptions that are occured in program
             *now you will take desired action what you want to do 
             **/
        }
    }

}

【讨论】:

  • 嗨,我喜欢你的解决方案!我不知道这是最好的做法 一个小东西,如果一个 setter 失败了,计数仍然是一样的。所以你有一个无限循环。也许您可以在切换之前递增,或者在 finally 组中递增?
  • 看看我的代码..有一个count++语句。在switch之后和catch块中有count++语句
  • 是的......但是for (count = 1; count &lt;= 6; count++) 做同样的事情,而且它更具可读性。另外,你应该抓住ProductException。捕获Exception 是个坏主意,因为它会导致将意外异常作为验证错误报告给用户。
  • 是的,很好。但我只是给你解决问题的想法。你可以根据你的要求修改它
【解决方案2】:

如果您需要列表中的所有异常,则必须通过 try catch 包围每一行并将异常添加到列表中,最后检查列表的大小是否大于 0,然后将该列表作为异常返回。

List<CustomException> exceptionList = new ArrayList<CustomException>();
public void editProduct(String articleNumber, ...) 
{
     try{
          product.setArticleNumber(articleNumber);
     }catch(CustomException exception)
     {
       exceptionList.add(exception);
      }
      try{
      product.setDescription(description);
      }catch(CustomException exception)
     {
       exceptionList.add(exception);
      }
     try{
     product.setLendable(lendable);
     }catch(CustomException exception)
     {
       exceptionList.add(exception);
      }
     try{
          product.setName(name);
     }catch(CustomException exception)
     {
       exceptionList.add(exception);
      }
      try{
       product.setPrice(price);
     }catch(CustomException exception)
     {
       exceptionList.add(exception);
      }
     try{
      product.setPlace(place);
     }catch(CustomException exception)
     {
       exceptionList.add(exception);
      }
}

【讨论】:

  • 谢谢,但是没有更好的解决方案吗?
  • 而不是从 setter 方法中抛出异常,您只需添加一个 validate 方法来处理您的所有 setter 检查并在那里为所有字段验证执行所有操作。这将是击球手方法。
  • 嗨,这是可能的。但我想将所有“域”代码保留在域类中。
【解决方案3】:

如果你真的想做这样的事情,你可以将属性设置委托给一个方法,该方法将捕获作为 lambda 运行的 setter,然后捕获可能的异常,或者将其添加到列表中:

class C {
    @FunctionalInterface
    private static interface TaskMayThrow {
        void run() throws CustomException;
    }

    private static boolean runTask(TaskMayThrow task, List<CustomException> errList) {
        try {
            task.run();
            return true;
        } catch(CustomException e) {
            errList.add(e);
            return false;
        }
    }

    List<CustomException> exceptionList = new ArrayList<CustomException>();
    public void editProduct(String articleNumber, ...) 
    {
         runTask(() -> product.setArticleNumber(articleNumber), exceptionList);
         runTask(() -> product.setDescription(description), exceptionList);
         // The same for all other setters
         // Do whatever you want with the error list
     }

【讨论】:

    猜你喜欢
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 2013-06-24
    • 2011-06-27
    相关资源
    最近更新 更多