Search code examples
javaexceptionpmdrethrow

Java error: New exception is thrown in catch block, original stack trace may be lost


try {
    // code which throws exception.
} catch (SQLException sqlex) {
    logger.error("Custom message", sqlex);
    **throw new CustomApplicationException("Custom message", sqlex);**
}

In the above example, on the bold line, I am getting PMD error as "New exception is thrown in catch block, original stack trace may be lost". I know this question has been asked many times also there are many online references available for the same. I have tried all the ways possible. But still I am not able to remove this PMD error. Please let me know whats wrong in this code slice. Thanks in advance!


Solution

  • I don't think there's anything wrong with that code.

    But I also, don't think that PMD will / should give that error for that code. IIRC, you get that error with something like this:

    try {
        // code which throws exception.
    } catch (SQLException sqlex) {
        throw new CustomApplicationException("Custom message");  // no cause!
    }
    

    It is possible that you have an old version of PMD or that someone has been "improving" the PMD rules that you are using.