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
How to resolve 'Define and throw a dedicated exception instead of using a generic one.'
提问by Kruti Patel
I need to throw RuntimeException
when length of two lists is not equal. We are using SonarQube
tool 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, 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.
现在,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, 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
.
如果这两个列表是传递给方法的参数,则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 然后抛出你的子类,这样异常的类型实际上提供了关于发生了什么的信息,允许函数的客户端适当地捕获和处理它。