1 package net.sourceforge.pmd.rules.design; 2 3 import net.sourceforge.pmd.AbstractRule; 4 import net.sourceforge.pmd.RuleContext; 5 import net.sourceforge.pmd.ast.ASTCatch; 6 import net.sourceforge.pmd.ast.ASTClassOrInterfaceType; 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 23 String throwName = node.getFirstClassOrInterfaceTypeImage(); 24 25 ASTTryStatement parent = (ASTTryStatement) node.getFirstParentOfType(ASTTryStatement.class); 26 if (parent == null) { 27 return data; 28 } 29 for (parent = (ASTTryStatement) parent.getFirstParentOfType(ASTTryStatement.class) 30 ; parent != null 31 ; parent = (ASTTryStatement) parent.getFirstParentOfType(ASTTryStatement.class)) { 32 33 List list = parent.getCatchBlocks(); 34 for (Iterator iter = list.iterator(); iter.hasNext();) { 35 ASTCatch catchStmt = (ASTCatch) iter.next(); 36 ASTType type = (ASTType) catchStmt.getFormalParameter().findChildrenOfType(ASTType.class).get(0); 37 ASTClassOrInterfaceType name = (ASTClassOrInterfaceType) type.findChildrenOfType(ASTClassOrInterfaceType.class).get(0); 38 39 if (throwName != null && throwName.equals(name.getImage())) { 40 addViolation((RuleContext) data, name); 41 } 42 } 43 } 44 return data; 45 } 46 47 }