Hi,
We want to check that we don't have the following code:
class A {
public void methodA1() {
try {
throw new Exception ("Don't compare");
} catch (Exception e) {
e.getMessage().contains("using contains"); // Noncompliant
}
}
}
I have managed to get contains() method but how can
I get the method call getMessage() on the exception?
br,
//mike
Using:
TryStatementTree tryStatement = (TryStatementTree) tree;
for (CatchTree catchTree : tryStatement.catches()) {
//get what is after (Exception e) that is { .....}
BlockTree block = catchTree.block();
//e.getMessage().conatins("message")
List<StatementTree> statementTrees = block.body();
for (StatementTree statementTree : statementTrees) {
if (statementTree.is(Tree.Kind.EXPRESSION_STATEMENT)) {
ExpressionTree expressionTree = ((ExpressionStatementTree) statementTree).expression();
if(expressionTree.is(Tree.Kind.METHOD_INVOCATION)){
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expressionTree;
Symbol symbol = methodInvocationTree.symbol();
System.out.println("Check catch");
}
}
}
}