質問

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);
    }
役に立ちましたか?

解決

    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

他のヒント

You can do this : (use an outside try catch)

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

You can do something like this

  try{
     // do some thing
    } catch (X |Y |Z | Exception e) {
        logFailure(e, parameter);
        throw new Exception(e);             
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top