【问题标题】:How to resolve 'Define and throw a dedicated exception instead of using a generic one.'如何解决“定义并抛出专用异常而不是使用通用异常”。
【发布时间】:2016-06-03 13:21:10
【问题描述】:

当两个列表的长度不相等时,我需要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));
            }

现在,SonarQubethrow new RuntimeException 行提出了Define and throw a dedicated exception instead of using a generic one. 的问题。我不知道我可以替换哪个异常来解决SonarQube 问题。

【问题讨论】:

  • 信息够清楚了。你有什么不明白的?

标签: java exception sonarqube


【解决方案1】:

如果这两个列表是传递给方法的参数,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));
}

【讨论】:

    【解决方案2】:

    Don't throw generic exceptions。您应该将 Exception 子类化,然后抛出您的子类,以便异常的类型实际上提供有关正在发生的事情的信息,从而允许函数的客户端捕获并适当地处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多