当两个列表的长度不相等时,我需要throw RuntimeException
。我们使用SonarQube
工具进行代码审查。
这是代码:
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));
}
现在,SonarQube
提出Define and throw a dedicated exception instead of using a generic one.
在throw new RuntimeException
线的问题。我不知道我可以替换哪个例外来解决SonarQube
问题。
如果这两个列表是传递给方法的参数,那么IllegalArgumentException
将是一个很好的候选者。它是RuntimeException
的一个子类,所以你仍然会抛出一种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));
}
Don't throw generic exceptions。您应该继承Exception,然后抛出您的子类,以便异常的类型实际上提供有关正在发生的事情的信息,允许该函数的客户端捕获并适当地处理它。