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

試著忘記壹切 提交于 2019-12-18 20:16:05

问题


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.


回答1:


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));
}



回答2:


Don't throw generic exceptions. You should be subclassing Exception and then throwing your subclass, so that the type of the exception actually provides information about what is going on, allowing clients of the function to catch and treat it appropriately.



来源:https://stackoverflow.com/questions/35548169/how-to-resolve-define-and-throw-a-dedicated-exception-instead-of-using-a-generi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!