How to find the method call on an exception

49 views
Skip to first unread message

mikael petterson

unread,
Jun 1, 2018, 3:57:45 AM6/1/18
to SonarQube
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");
                     
                      
                    }
                }

          
               

            }

        }

Andrei Epure

unread,
Jun 11, 2018, 3:52:01 AM6/11/18
to SonarQube
Hello Mike,

You're very close, the below snippet should help.

    if (tree.is(Tree.Kind.METHOD_INVOCATION)) {
     
MethodInvocationTree mit = (MethodInvocationTree) tree; // String#contains()
     
if (mit.methodSelect().is(Tree.Kind.MEMBER_SELECT)) {
       
MemberSelectExpressionTree mset = (MemberSelectExpressionTree) mit.methodSelect();
       
if (mset.expression().is(Tree.Kind.METHOD_INVOCATION)) {
         
MethodInvocationTree leftMit = (MethodInvocationTree) mset.expression(); // Throwable#getMessage()
         
System.out.println(leftMit);
       
}
     
}
   
}


Thanks,
Andrei

Andrei Epure | SonarSource

Software Developer

https://sonarsource.com


Are you using SonarLint in your IDE?


Reply all
Reply to author
Forward
0 new messages