- Home
- PMD and CPD
- How to create PMD custom rule in ruleset
Writing PMD rules is cool, after reading this post you will
say how easy is to implement PMD.
To implement we need eclipse needs installed with PMD.
You should not download anything. Instead, simply add
following URL as new update site in Eclipse -> Help -> Install new
software:
http://pmd.sourceforge.net/eclipse
Then select appropriate Eclipse PMD plugin and you are done.

Java or XPath?
There are two ways to write rules:
- Write a rule using Java
- Write an XPath expression
Here easy way to implements custom rules in XPath expression.
Figure out what you want
to look for
Lets's figure out what
problem we want to spot.
Write sample program which
will indicate your expectation coding standard.
As of now I am taking
Examples for Exception handling.
1. CatchNeedThrowStatment
public class PMDCheck {
public void pmdValidate() throws Exception {
String s = null;
try {
s="Welcome Sample PMD Custom rule";
System.out.println(s);
} catch (Exception e) {
throw new Exception("Exception in PMDCheck.pmdValidate"+e);
}
}
}
This is my sample program,
expecting throw statement if I am catching Exception.
To write XPath we need to
know the level to form expression for that. Generate Abstract Syntax Tree(AST)
for sample program by using PMD-> Generate Abstract Syntax Tree.

<?xml version="1.0" encoding="UTF-8"?>
<CompilationUnit>
=====
<CatchStatement>
===
<ThrowStatement>
==
</ThrowStatement>
</CatchStatement>
</CompilationUnit>
I am expecting throw
statement in catch.
So I am using below XPath
expression to handle above scenario
//CatchStatement[not(descendant::ThrowStatement)]
Add above expression in Window->Preferences->PMD-Rule
Configuration->Add Rule
Enter rule name, ruleset
name, and priority selected

Next
Enter description and message

Next->Next
Enter XPath Expression

Make sure your PMD rule, check box should check for project
Project properties->PMD

Check code with PMD right, click->PMD-CheckCode

See now how rule working to evaluate our code with our own rule:
