java 如何解决“定义并抛出专用异常而不是使用通用异常”。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35548169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:15:52  来源:igfitidea点击:

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

javaexceptionsonarqube

提问by Kruti Patel

I need to throw RuntimeExceptionwhen length of two lists is not equal. We are using SonarQubetool for code review purpose.

throw RuntimeException当两个列表的长度不相等时,我需要这样做。我们正在使用SonarQube工具进行代码。

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, SonarQuberaises issue that Define and throw a dedicated exception instead of using a generic one.at throw new RuntimeExceptionline. I don't know which exception I can replace to resolve SonarQubeissue.

现在,SonarQube加薪颁发Define and throw a dedicated exception instead of using a generic one.throw new RuntimeException线。我不知道我可以替换哪个异常来解决SonarQube问题。

回答by Eran

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

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

回答by Tim Jasko

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.

不要抛出通用异常。你应该子类化 Exception 然后抛出你的子类,这样异常的类型实际上提供了关于发生了什么的信息,允许函数的客户端适当地捕获和处理它。