enrique marmolejo
enrique marmolejo

Reputation: 3

Why SonarQube complains about generic Exception when the exception has been changed to custom one

I've been tasked to make JUnit tests for an application that someone else made along time, I can't modify the original code, so when I encounter something like this:

public String clean(String url) throws Exception {
    if (url.indexOf(invalidURL) {
        throw new Exception("Severe XSSS detected");
    }
}

I write my test with: throws Exception, and SonarQube complains about generic Exception and if I write a custom exception like: public class MyException extends Exception, still SonarQube doesn't like it, any help will be much appreciated!

Upvotes: 0

Views: 797

Answers (3)

David M. Karr
David M. Karr

Reputation: 15235

The existing answers provide useful information, but if the constraints you specify in your original post are correct, those answers don't really help.

If you can't actually modify the code under test, there is no way you can fix the SonarQube issue.

Upvotes: 0

agabrys
agabrys

Reputation: 9136

MyException extends Exception, so you have to change the method declaration too - the throws statement:

public String clean(String url) throws MyException {
   if (url.indexOf(invalidURL) {
      throw new MyException("Severe XSSS detected");
   }
}

The change is safe because the code is compatible with the previous option:

try {
    object.clean("invalidUrl")
} catch (Exception e) {
    // MyException is handled by this catch block
}

Upvotes: 0

McPringle
McPringle

Reputation: 2139

I'm interpreting your code: Looks like you have an invalid URL somewhere and you don't want to do your business stuff, if the parameter url contains this invalid URL. So I would guess that an IllegalArgumentException is much more precise than the generic Exception.

From the JavaDoc of IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Furthermore, I would assume that SonarQube will accept an IllegalArgumentException at this point without grumbling.

Upvotes: 1

Related Questions