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.ASTClassOrInterfaceType;
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 *
15 * @author <a mailto:trondandersen@c2i.net>Trond Andersen</a>
16 */
17 public class AvoidCatchingThrowable extends AbstractRule {
18
19
20 public Object visit(ASTTryStatement tryStmt, Object o) {
21
22 if (!tryStmt.hasCatch()) {
23 return super.visit(tryStmt, o);
24 }
25
26
27 for (int i = 0; i < tryStmt.getCatchBlocks().size(); i++) {
28 evaluateCatch((ASTCatch) tryStmt.getCatchBlocks().get(i), (RuleContext) o);
29 }
30 return super.visit(tryStmt, o);
31 }
32
33 /***
34 * Checking the catch statement
35 *
36 * @param aCatch CatchBlock
37 * @param ruleContext
38 */
39 private void evaluateCatch(ASTCatch aCatch, RuleContext ruleContext) {
40 ASTType type = (ASTType) aCatch.getFormalParameter().findChildrenOfType(ASTType.class).get(0);
41 ASTClassOrInterfaceType name = (ASTClassOrInterfaceType) type.findChildrenOfType(ASTClassOrInterfaceType.class).get(0);
42
43 if (name.getImage().equals("Throwable")) {
44 ruleContext.getReport().addRuleViolation(createRuleViolation(ruleContext, name));
45 }
46 }
47 }