01: package org.acm.seguin.pmd.rules.strictexception;
02:
03: import org.acm.seguin.pmd.AbstractRule;
04: import org.acm.seguin.pmd.RuleContext;
05: import net.sourceforge.jrefactory.ast.ASTFormalParameter;
06: import net.sourceforge.jrefactory.ast.ASTReferenceType;
07: import net.sourceforge.jrefactory.ast.ASTTryStatement;
08: import net.sourceforge.jrefactory.ast.ASTClassOrInterfaceType;
09: import net.sourceforge.jrefactory.ast.ASTType;
10: import net.sourceforge.jrefactory.ast.Node;
11:
12: /**
13: * PMD rule which is going to find <code>catch</code> statements
14: * containing <code>throwable</code> as the type definition.
15: * <p>
16: * @author <a mailto:trondandersen@c2i.net>Trond Andersen</a>
17: */
18: public class AvoidCatchingThrowable extends AbstractRule {
19:
20: public Object visit(ASTTryStatement astTryStatement,
21: Object ruleContext) {
22: // Requires a catch statement
23: if (!astTryStatement.hasCatch()) {
24: return super .visit(astTryStatement, ruleContext);
25: }
26:
27: /* Checking all catch statements */
28: int lastIndex = astTryStatement.jjtGetNumChildren();
29: for (int ndx = 0; ndx < lastIndex; ndx++) {
30: Node next = astTryStatement.jjtGetChild(ndx);
31: if (next instanceof ASTFormalParameter) {
32: evaluateCatch((ASTFormalParameter) next,
33: (RuleContext) ruleContext);
34: }
35: }
36: return super .visit(astTryStatement, ruleContext);
37: }
38:
39: /**
40: * Checking the catch statement
41: * @param aCatch CatchBlock
42: * @param ruleContext
43: */
44: private void evaluateCatch(ASTFormalParameter aCatch,
45: RuleContext ruleContext) {
46: ASTType type = (ASTType) aCatch.findChildrenOfType(
47: ASTType.class).get(0);
48: ASTReferenceType ref = (ASTReferenceType) type
49: .findChildrenOfType(ASTReferenceType.class).get(0);
50: ASTClassOrInterfaceType name = (ASTClassOrInterfaceType) ref
51: .findChildrenOfType(ASTClassOrInterfaceType.class).get(
52: 0);
53:
54: String image = name.getImage();
55: if ("Throwable".equals(image)
56: || "java.lang.Throwable".equals(image)) {
57: ruleContext.getReport().addRuleViolation(
58: createRuleViolation(ruleContext, name
59: .getBeginLine()));
60: }
61: }
62: }
|