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

mai*_*yok 3 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);
    }
Run Code Online (Sandbox Code Playgroud)

如果我将上面的代码改为下面,有3个重复的logFailure(e),有没有更好的方法来消除这种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);
    }
Run Code Online (Sandbox Code Playgroud)

Red*_*ddy 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);
    }
Run Code Online (Sandbox Code Playgroud)

此外,您可以移动Logger到此method,取决于您的设计/应用程序