View Javadoc

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