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:
Then select appropriate Eclipse PMD plugin and you are done.

PMD plugin option

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";
		} 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.

generate AST for PMD

<?xml version="1.0" encoding="UTF-8"?>

I am expecting throw statement in catch.
So I am using below XPath expression to handle above scenario

Add above expression in Window->Preferences->PMD-Rule Configuration->Add Rule
Enter rule name, ruleset name, and priority selected

add custom rule in PMD

Enter description and message

add custom rule description in PMD

Enter XPath Expression

PMD custom xpath expression

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

project properties for pmd rules

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

Check code with PMD

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

PMD results with custom rules