简体   繁体   中英

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. "

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.

Then have a condition checks the content of the string to throw a more specific custom checked exception (extends Exception).

How do I actually accomplish this without violating SonarQubes rule that I not throw new CheckedException(message); ?

Does this rule mean that SonarQube never wants the developer to throw a new custom checked exception?

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.

Personally I think that checked exception are a bit annoying but I wouldn't enable this rule, I don't find it relevant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM