如何在不违反 SonarQube 的情况下抛出检查异常?
How can you throw a checked exception without violating SonarQube?
SonarQube 规则规定“...no method throws a new checked exception.”
它给出了以下代码示例:
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();
}
那你怎么能真正抛出一个自定义检查的异常呢?
假设我捕获了 IOException 并执行 getMessage() 以获取 IOException 的详细消息字符串。
然后有条件检查字符串的内容以抛出更具体的自定义检查异常(扩展异常)。
我如何在不违反我不 throw new CheckedException(message);
的 SonarQubes 规则的情况下实际完成此操作?
这条规则是否意味着 SonarQube 永远不希望开发人员抛出新的自定义检查异常?
这是来自规则
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.
这不是绝对的规则。
如果您想阻止人们在您的代码中抛出已检查的异常,这完全取决于您。
请记住,Sonar 规则只是规则,如果您不同意某些规则,只需禁用它们即可。
特别是这个看起来非常基于意见。
如果您无法禁用它,请将问题解决为 won't fix
并添加注释以说明您需要抛出此异常,因为架构需要如此。
我个人认为检查异常有点烦人,但我不会启用此规则,我认为它不相关。
SonarQube 规则规定“...no method throws a new checked exception.”
它给出了以下代码示例:
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();
}
那你怎么能真正抛出一个自定义检查的异常呢?
假设我捕获了 IOException 并执行 getMessage() 以获取 IOException 的详细消息字符串。
然后有条件检查字符串的内容以抛出更具体的自定义检查异常(扩展异常)。
我如何在不违反我不 throw new CheckedException(message);
的 SonarQubes 规则的情况下实际完成此操作?
这条规则是否意味着 SonarQube 永远不希望开发人员抛出新的自定义检查异常?
这是来自规则
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.
这不是绝对的规则。
如果您想阻止人们在您的代码中抛出已检查的异常,这完全取决于您。
请记住,Sonar 规则只是规则,如果您不同意某些规则,只需禁用它们即可。
特别是这个看起来非常基于意见。
如果您无法禁用它,请将问题解决为 won't fix
并添加注释以说明您需要抛出此异常,因为架构需要如此。
我个人认为检查异常有点烦人,但我不会启用此规则,我认为它不相关。