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.List;
12  
13  /**
14   * Catches the use of exception statements as a flow control device.
15   *
16   * @author Will Sargent
17   */
18  public class ExceptionAsFlowControl extends AbstractRule {
19  
20      public Object visit(ASTThrowStatement node, Object data) {
21          ASTTryStatement parent = node.getFirstParentOfType(ASTTryStatement.class);
22          if (parent == null) {
23              return data;
24          }
25          for (parent = parent.getFirstParentOfType(ASTTryStatement.class)
26                  ; parent != null
27                  ; parent = parent.getFirstParentOfType(ASTTryStatement.class)) {
28  
29              List<ASTCatchStatement> list = parent.findChildrenOfType(ASTCatchStatement.class);
30              for (ASTCatchStatement catchStmt: list) {
31                  ASTFormalParameter fp = (ASTFormalParameter) catchStmt.jjtGetChild(0);
32                  ASTType type = fp.findChildrenOfType(ASTType.class).get(0);
33                  ASTClassOrInterfaceType name = type.findChildrenOfType(ASTClassOrInterfaceType.class).get(0);
34                  if (node.getFirstClassOrInterfaceTypeImage() != null && node.getFirstClassOrInterfaceTypeImage().equals(name.getImage())) {
35                      addViolation(data, name);
36                  }
37              }
38          }
39          return data;
40      }
41  
42  }