xbmono
xbmono

Reputation: 2316

How to create a custom Sonar rule to check if a method throws a certain exception?

So we want to check a certain method, say findOne() in certain java classes if it throws a specific exception or not. If it doesn't throw the exception, then an issue to be reported at method level.

We could use

public void visitThrowStatement(ThrowStatementTree tree)

but this only gets called when there is a statement that throws the exception, how can we check if it's not thrown?

Upvotes: 0

Views: 551

Answers (1)

benzonico
benzonico

Reputation: 10833

You need to keep a context in your visitor to know in which method you are currently visiting throw statements.

Basically, if you are within a findOne method, then you will visit the code of the method, if it has a correct throw statement,then don't raise an issue but if it has not then raise an issue.

Something along the lines of (this is pseudo code and should of course be adapted but that will explain the concept):

LinkedList<MethodTree> stack;
int throwCount = 0;
void visitMethod(MethodTree methodTree) {
   stack.push(methodTree);
   throwCount = 0;
   super.visitMethod(methodTree);
   if(throwCount == 0) {
      //raise Issue
   }
}

void visit throwStatement(ThrowStatementTree tree) {
   if(isCorrectExceptionThrown(tree)) {
     throwCount++;
   }
}

Upvotes: 1

Related Questions