[英]How can you throw a checked exception without violating SonarQube?
There is a SonarQube rule that states that " ...no method throws a new checked exception. " 有一个SonarQube规则,该规则指出“ ...没有方法抛出新的已检查异常。 ”
And it gives the following code example: 并给出以下代码示例:
public void myMethod1() throws CheckedException {
...
throw new CheckedException(message); // Noncompliant
...
throw new IllegalArgumentException(message); // Compliant; IllegalArgumentException is unchecked
}
public void myMethod2() throws CheckedException { // Compliant; propagation allowed
myMethod1();
}
How then can you actually throw a custom checked exception? 那么如何才能实际引发自定义检查异常?
Let's say I catch a IOException and do a getMessage() to get the detail message string of the IOException. 假设我捕获了IOException并执行getMessage()以获取IOException的详细消息字符串。
Then have a condition checks the content of the string to throw a more specific custom checked exception (extends Exception). 然后让条件检查字符串的内容以引发更特定的自定义检查异常(扩展Exception)。
How do I actually accomplish this without violating SonarQubes rule that I not throw new CheckedException(message);
在不违反SonarQubes规则(我不
throw new CheckedException(message);
情况下,我如何实际完成此操作throw new CheckedException(message);
? ?
Does this rule mean that SonarQube never wants the developer to throw a new custom checked exception? 这条规则是否意味着SonarQube从不希望开发人员抛出新的自定义检查异常?
This is from the rule 这是从规则
The purpose of checked exceptions is to ensure that errors will be dealt with, either by propagating them or by handling them, but some believe that checked exceptions negatively impact the readability of source code, by spreading this error handling/propagation logic everywhere.
检查异常的目的是确保通过传播错误或通过处理错误来处理错误, 但有些人认为 ,通过将错误处理/传播逻辑传播到各处,检查异常会对源代码的可读性产生负面影响。
This rule verifies that no method throws a new checked exception.
该规则验证没有方法抛出新的检查异常。
It's not an absolute rule. 这不是绝对的规则。 It's just up to you if you want to prevent people from throwing checked exceptions in your code.
如果要防止人们在代码中引发检查异常,这取决于您。
Remember that Sonar rules are just rules, if you don't agree with some, simply disable them. 请记住,声纳规则只是规则,如果您不同意某些规则,只需禁用它们即可。 This one in particular looks very opinion-based.
尤其是这个看起来很基于意见。
If you can't disable it, resolve the issue as won't fix
and add a comment to explain that you need to throw this exception because the architecture requires so. 如果你无法禁用它,作为解决该问题
won't fix
,并添加评论,说明你需要抛出此异常,因为结构需要如此。
Personally I think that checked exception are a bit annoying but I wouldn't enable this rule, I don't find it relevant. 我个人认为检查异常有点烦人,但我不会启用此规则,我认为它不相关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.