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