diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/PreserveStackTraceRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/PreserveStackTraceRule.java index 8f8576e905..9aaceef4cb 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/PreserveStackTraceRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/PreserveStackTraceRule.java @@ -140,9 +140,8 @@ public class PreserveStackTraceRule extends AbstractJavaRule { if (target != null && baseNode != null) { List nameNodes = baseNode.findDescendantsOfType(ASTName.class); for (ASTName nameNode : nameNodes) { - if (target.equals(nameNode.getImage())) { - boolean isPartOfStringConcatenation = - (nameNode.jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTAdditiveExpression); + if (target.equals(nameNode.getImage())) { + boolean isPartOfStringConcatenation = isStringConcat(nameNode, baseNode); if (!isPartOfStringConcatenation) { match = true; break; @@ -152,6 +151,23 @@ public class PreserveStackTraceRule extends AbstractJavaRule { } return match; } + /** + * Checks whether the given childNode is part of an additive expression (String concatenation) limiting search to base Node. + * @param childNode + * @param baseNode + * @return + */ + private boolean isStringConcat(Node childNode, Node baseNode) { + Node currentNode = childNode; + // limit to 10 levels + for (int i = 0; i < 10 && currentNode != null && currentNode != baseNode; i++) { + currentNode = currentNode.jjtGetParent(); + if (currentNode instanceof ASTAdditiveExpression) { + return true; + } + } + return false; + } private void ck(Object data, String target, ASTThrowStatement throwStatement, Node baseNode) { if (!checkForTargetUsage(target, baseNode)) { diff --git a/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/PreserveStackTrace.xml b/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/PreserveStackTrace.xml index fc95008bd2..1900c10786 100644 --- a/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/PreserveStackTrace.xml +++ b/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/PreserveStackTrace.xml @@ -542,14 +542,18 @@ public class Bug { #543 False negative with String concatenation - 1 + 3