Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve 'Define and throw a dedicated exception instead of using a generic one.'

I need to throw RuntimeException when length of two lists is not equal. We are using SonarQube tool for code review purpose.

Here is the code:

if (objctArray.length != columnArray.length) {
                throw new RuntimeException(String.format("objctArray and columnArray length is not same. objctArray length = %d, columnArray length = %d", objctArray.length, columnArray.length));
            }

Now, SonarQube raises issue that Define and throw a dedicated exception instead of using a generic one. at throw new RuntimeException line. I don't know which exception I can replace to resolve SonarQube issue.

like image 356
Kruti Patel Avatar asked Feb 22 '16 07:02

Kruti Patel


1 Answers

If those two lists are arguments passed to a method, IllegalArgumentException would be a good candidate to throw. It's a sub-class of RuntimeException, so you'll still be throwing a kind of RuntimeException.

if (objctArray.length != columnArray.length) {
    throw new IllegalArgumentException(String.format("objctArray and columnArray length is not same. objctArray length = %d, columnArray length = %d", objctArray.length, columnArray.length));
}
like image 113
Eran Avatar answered Sep 17 '22 12:09

Eran