Java:如何重构这种try-catch块?

时间:2013-07-19 09:08:49

标签: java refactoring try-catch pmd

PMD报告“正在对捕获的异常执行检查实例。为此异常类型创建单独的catch子句。”以下代码。

    String parameter;
    try {
        ...
    } catch (Exception e) {
        logFailure(e, parameter);

        if (e instanceof X) {
            throw new A(e);
        } else if (e instanceof Y
                || e instanceof Z) {
            throw new B(e);
        } 
        throw new InternalServerErrorException(e);
    }

如果我将上面的代码更改为以下代码,则logFailure(e)有3个重复,有没有更好的方法来消除这种PMD违规?

    String parameter;
    try {
        ...
    } catch (X e) {
        logFailure(e, parameter);
        throw new A(e);
    } catch (Y e) {
        logFailure(e);
        throw new B(e);
    } catch (Z e) {
        logFailure(e);
        throw new B(e);
    } catch (exception e) {
        logFailure(e);
        throw new InternalServerErrorException(e);
    }

3 个答案:

答案 0 :(得分:8)

    String parameter;
    try {
        ...
    } catch (Exception e) {
        logFailure(e, parameter);
        throwException(e);
    }

    public void throwException(Exception e) throws Exception{
       if (e instanceof X) {
            throw new A(e);
        } else if (e instanceof Y
                || e instanceof Z) {
            throw new B(e);
        } 
        throw new InternalServerErrorException(e);
    }

此外,您可以将Logger移至此method,具体取决于您的设计/应用

答案 1 :(得分:2)

你可以这样做:(使用外部尝试捕获)

 String parameter;
 try {
    try {
        ...
    } catch (Exception e) {
        logFailure(e, parameter);
        throw e;
    }
 } catch (X e) {
        throw new A(e);
 } catch (Y e) {  
        throw new B(e);
 } catch (Z e) {
        throw new B(e);
 } catch (exception e) {
        throw new InternalServerErrorException(e);
 }
}

答案 2 :(得分:0)

你可以做这样的事情

  try{
     // do some thing
    } catch (X |Y |Z | Exception e) {
        logFailure(e, parameter);
        throw new Exception(e);             
    }
相关问题