How to get arguments of throw statement?

java

(Vanessa Guedes) #1

Good afternoon.

I’m starting in Sonar and I need to create a rule that verify if a throw statement is launched with a message passed as argument or not, as example, “throw new ServiceException (e)”. I’m trying to use ThrowStatementTree, but there isn’t a method to get the argument. How can I do it? I’m using Sonar 5.6.7. Thank you.


(Evgeny Mandrikov) #2

(Vanessa Guedes) #3

Hi, Godin. Thank you for answer. Sorry for my inexperience. I used expression method and tried to manipulate it but I only get the object. I tried to use IdentifierTree to get the value of the expression, but without sucess. I tried to use arguments with NewClassTree but without sucess too. How can I get the argument value?


(Michael Gumowski) #5

Hello Vanessa,

Please share the code of your custom rule if you want some help. It would be easier (removing eventual business logic).

By the way, did you follow the tutorial to write custom java rules? It should have give you a few tips on how to navigate and test trees.

Now, @Godin gave you already almost everything you need. You just need to connect the dots.

  • From the expression of the throw statement, check if it’s a call to a constructor (expression.is(Tree.Kind.NEW_CLASS)),
  • then cast to NewClassTree,
  • then get the arguments,
  • then check their types
  • if none is a String -> report an issue (is it your use case?)

Cheers,
Michael


(Vanessa Guedes) #7

Yes, Michael. It’s what I wanted. I already got it. As I hadn’t a more detailed explanation before, I searched internet and I saw a post from you in another site about a similar question. Then I followed it to based my research and I was able to develop the rule.

Thanks for your attention.