Java: How to refactor this kind of try-catch block?

java, pmd, refactoring, try-catch

Solution

    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);
    }

Additionally you can move `Logger` to this `method`, depends on your design/application

Problem

PMD report that "An instanceof check is being performed on the caught exception. Create a separate catch clause for this exception type." for below code. ``` 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); } ``` if i change above code to below, there are 3 duplication of logFailure(e), is there any better way to eliminate this kind of PMD violation? ``` 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); } ```

Original source