View Javadoc

    1   package net.sourceforge.pmd.lang.java.rule.strictexception;
    2
    3   import java.util.List;
    4
    5   import net.sourceforge.pmd.lang.java.ast.ASTCatchStatement;
    6   import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
    7   import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
    8   import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement;
    9   import net.sourceforge.pmd.lang.java.ast.ASTTryStatement;
    10  import net.sourceforge.pmd.lang.java.ast.ASTType;
    11  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
    12
    13  /**
    14   * Catches the use of exception statements as a flow control device.
    15   *
    16   * @author Will Sargent
    17   */
    18  public class ExceptionAsFlowControlRule extends AbstractJavaRule {
    19
    20      @Override
    21      public Object visit(ASTThrowStatement node, Object data) {
    22          ASTTryStatement parent = node.getFirstParentOfType(ASTTryStatement.class);
    23          if (parent == null) {
    24              return data;
    25          }
    26          for (parent = parent.getFirstParentOfType(ASTTryStatement.class)
    27                  ; parent != null
    28                  ; parent = parent.getFirstParentOfType(ASTTryStatement.class)) {
    29
    30              List<ASTCatchStatement> list = parent.findDescendantsOfType(ASTCatchStatement.class);
    31              for (ASTCatchStatement catchStmt: list) {
    32                  ASTFormalParameter fp = (ASTFormalParameter) catchStmt.jjtGetChild(0);
    33                  ASTType type = fp.getFirstDescendantOfType(ASTType.class);
    34                  ASTClassOrInterfaceType name = type.getFirstDescendantOfType(ASTClassOrInterfaceType.class);
    35                  if (node.getFirstClassOrInterfaceTypeImage() != null && node.getFirstClassOrInterfaceTypeImage().equals(name.getImage())) {
    36                      addViolation(data, name);
    37                  }
    38              }
    39          }
    40          return data;
    41      }
    42
    43  }