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

- 137,514
- 11
- 162
- 243
-
Using RuntimeException could solve the problem, but I think RuntimeException is - to follow the idea of Sonar individual handling of exceptions - also generic. In my concrete case I'm using Jaxb to unmarshall a XML string. Compiler says me only about JAXBException, but now when the XML string contains something like &foo (without semicolon) in a value, the exception is com.ctc.wstx.exc.WstxLazyException. – Nader Mar 02 '18 at 09:49
-
@Nader it is also generic, but it's an unchecked exception: you're not *really* meant to try to (or be able to) recover from it in a meaningful way, because it indicates a programming error. It's reasonable just to say "meh, a problem occurred; don't tear down the world, but there's nothing to be done". A checked exception, on the other hand, is meant to indicate something that you should be able to do something to recover from (e.g. retry, because I was only interrupted on this invocation, and it may succeed next time). – Andy Turner Mar 02 '18 at 09:57
-
-
1@Nader you may want to read https://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation – Andy Turner Mar 02 '18 at 10:18
-