1 package net.sourceforge.pmd.rules.strictexception;
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.ASTName;
7 import net.sourceforge.pmd.ast.ASTTryStatement;
8 import net.sourceforge.pmd.ast.ASTType;
9
10 /***
11 * PMD rule which is going to find <code>catch</code> statements
12 * containing <code>throwable</code> as the type definition.
13 * <p>
14 * @author <a mailto:trondandersen@c2i.net>Trond Andersen</a>
15 */
16 public class AvoidCatchingThrowable extends AbstractRule {
17
18
19 public Object visit(ASTTryStatement astTryStatement, Object o) {
20
21 if (!astTryStatement.hasCatch()) {
22 return super.visit(astTryStatement, o);
23 }
24
25
26 for (int i = 0; i < astTryStatement.getCatchBlocks().size(); i++) {
27 evaluateCatch((ASTCatch) astTryStatement.getCatchBlocks().get(i), (RuleContext) o);
28 }
29 return super.visit(astTryStatement, o);
30 }
31
32 /***
33 * Checking the catch statement
34 * @param aCatch CatchBlock
35 * @param ruleContext
36 */
37 private void evaluateCatch(ASTCatch aCatch, RuleContext ruleContext) {
38 ASTType type = (ASTType)aCatch.getFormalParameter().findChildrenOfType(ASTType.class).get(0);
39 ASTName name = (ASTName)type.findChildrenOfType(ASTName.class).get(0);
40
41 if (name.getImage().equals("Throwable")) {
42 ruleContext.getReport().addRuleViolation(createRuleViolation(ruleContext, name.getBeginLine()));
43 }
44 }
45 }