问题
Sonar complains when catching the generic type Exception, but sometimes we need to do some general exception handling for ALL (even not yet recognized) exception types. What is the solution to pass this sonar check?
回答1:
Unless you are invoking a method which throws Exception
, there is no need to catch Exception
: catch the exceptions you know about, and the compiler will tell you when you have to start handling another one.
The problem with catching "not yet recognized" Exception
s is that you lose the signal that you have to handle a new exception in a special way.
For example:
void someMethod() {
// Do stuff.
}
void callIt() {
try {
someMethod();
} catch (Exception e) {
// ...
}
}
If someMethod
is now changed so that it throws, say, an InterruptedException
:
void someMethod() throws InterruptedException {
Thread.sleep(1000);
// Do stuff.
}
you aren't told by the compiler that you need to add handling for the InterruptedException
in callIt()
, so you will silently swallow interruptions, which may be a source of problems.
If, instead, you had caught RuntimeException
, or RuntimeException | IOException | OtherExceptionYouAlreadyKnowAbout
, the compiler would flag that you had to change your code to handle that InterruptedException
as well; or, that you can't change the signature of someMethod()
, and the checked exception has to be handled there.
来源:https://stackoverflow.com/questions/49065496/sonarqube-avoiding-catch-generic-exception