【问题标题】:Retrieve value from exception handling e in java从java中的异常处理e中检索值
【发布时间】:2014-02-14 19:32:37
【问题描述】:

我有兴趣检查异常值,如果我将状态设置为特定值,然后想将货币字符串返回/设置为相应的错误,这可能是用户在客户端抛出错误。

/*code snippet */

       cr.setName(Name);
       cr.setContact(User);
       cr.setValue(Value);
       cr.setStatus(status);

       try
            {
                currency = (serviceCountry.createCurrencyTicket( cr, null ));

                if ( testPattern( currency ) )
                {
                    return currency;
                }

            }
            catch ( Exception e )
            {
                this.logger.log( Level.WARNING,
                                "Exception occured while evaluating currency = "
                                                + currency, params );                
            }

例如,异常 e 有 response、cause、stackTrace 对象。我想从响应中检索值并将货币设置为特定的错误。像

catch ( Exception e )
{
  if ( e.getClass().getName().getStatus() == 2 )
   {
    currency = 'ERROR';
   } else if ( e.getClass().getName().getStatus() == 0 )
   {
    currency = 'DOWN';
   }
}

【问题讨论】:

  • 您的问题是什么?您面临什么问题?
  • e.getClass().getName().getStatus()???这是什么意思。 AFIK getName 返回一个字符串,而字符串没有 getStatus
  • 从 Exception 开始是不好的做法;您最好先捕获更具体的异常。 Exception 还捕获未经检查的异常...
  • 我无法做到这一点 e.getClass().getName().getStatus(),我找不到 getStatus() 方法。
  • @Mad-D 你的函数是否抛出了自定义异常?

标签: java exception object exception-handling try-catch


【解决方案1】:

捕获实际抛出的异常类型是一种选择

try
{
     currency = (serviceCountry.createCurrencyTicket( cr, null ));
}catch(MyCustomException ex)
{
     if( ex.getStatus() == 2 )
         currency = "Oh Nos";
     else if( ex.getStatus() == 0 )
         currency = "Ehh";
}catch(Exception e)
{
     currency = "SuperBad";
}

另一个虽然乏味的选择是检查抛出的异常的类型

try
{
     currency = (serviceCountry.createCurrencyTicket( cr, null ));
}catch(Exception e)
{
     if( e instanceof MyCustomException )
     {
         MyCustomException customEx = (MyCustomException)e;
         if( customEx.getStatus() == 2 )
             currency = "Oh Nos";
         else if( customEx.getStatus() == 0 )
             currency = "Ehh";
     }
     else
         currency = "SuperBad";
}

【讨论】:

  • 但是第二种方案是一个很好理解的方案,因为它在与异常无关的其他领域很有价值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2010-10-31
  • 2015-03-09
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多