用于检查不同异常条件的大量if / else块的替代方案?

时间:2011-07-11 20:00:27

标签: java exception-handling if-statement

除了像这样的大量if / else块之外,还有更优雅的方法来检查所有可能的异常类型吗?

public ModelAndView resolveException(HttpServletRequest request, 
HttpServletResponse response, Object obj, Exception e) {

    if (e instanceof BadException)
    {
      displayMessage("That was bad.");
    }

    else if (e instanceof ReallyBadException)
    {
      displayMessage("That was really bad.");
    }

    else if (e instanceof ReallyReallyBadException)
    {
      displayMessage("That was really really bad.");
    }

    // ...
    // and so on
    // ...

    return null;
}

4 个答案:

答案 0 :(得分:2)

如果您控制最终出现在此方法中的异常,您可以使用其中嵌入的消息:

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) {
    displayMessage(e.getMessage());
    return null;
}

但是,如果消息对最终用户有意义,则应该只执行此操作。通常,您应该以用户没有注意到任何错误的方式处理异常。

答案 1 :(得分:2)

public ModelAndView resolveException(HttpServletRequest request, 
        HttpServletResponse response, Object obj, Exception exception)
{
    try
    { 
        throw exception;
    }
    catch(BadException e)
    {
        displayMessage("That was bad.");
    } catch (ReallyBadException e)
    {
      displayMessage("That was really bad.");
    } catch (ReallyReallyBadException e)
    {
      displayMessage("That was really really bad.");
    }

    // ...
    // and so on
    // ...

    return null;
}

答案 2 :(得分:1)

使用多个catch块see here

答案 3 :(得分:0)

您可以为要显示的消息创建预定义的特定异常类型的地图:

private Map<Class<?>, String> exceptionMessages = ...;

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) {

    if exceptionMessages.containsKey(e.getClass()) {
        displayMessage(exceptionMessages.get(e.getClass()));
    }
    else {
         // what to do by default?
    }
    return ...;
}

甚至更好,您可以将Map外部化为属性文件或ResourceBundle,这样您就可以从代码以外的某个地方加载用户可见的字符串(和/或将其全局化)。

此代码示例无法处理为异常类型的层次结构使用相同的消息,但如果在地图中找不到直接类,则遍历继承链应该非常简单。