"Don't catch generic Exceptions!" But how to unravel them?
error-handling, exception, java, static-analysis
Solution
The most important thing about catching general Exceptions is where you catch them, not whether. If you do it at a central place, a so-called exception barrier, which is high up in the call stack, then that is exactly what you should be doing. It would be a bad practice if you did it in the middle of your code, at some more or less arbitrary point.
Problem
Most of the static code analysis tools suggest not to catch generic (in particular unchecked) exceptions like RuntimeExceptions and Errors. Unless this Exception barrier might be reasonable at a top level, generally it isn't at a lower level. Unfortunately this can be very difficult to achive when rewriting/fixing already existing code, because the underlying possibilities of possible Errors and RuntimeExceptions can be exorbitant. Moreover, it is mostly a really time consuming and complex task to dig into the lower code levels to gain some ideas of Exceptions reasonable enough to catch instead of the generic catch. Do you know any tools or best practices to unravel such generic (unchecked) exceptions into more specific ones? say we have something like that: ``` try { somethingReallyComplex(); } catch (RuntimeException | Error ex) { Logger.error(this, ex.getClass().getName() + " while doing something really complex", ex) } ``` The try block can contain a really complex matter of code with a variety of different RuntimeExceptions and Errors which make sense to catch. But how can I analyse this code most effectively to unravel the RuntimeException into NullPointerException, ArrayIndexOutOfBoundException... whatever might be reasonable? Are there any tools that can analyze such code and give suggestions about most common RuntimeExceptions in there and the like? How do you start to solve this problem? Where is the subjective or objective "threshold" to say: "No, I just leave it as RuntimeException and add a suppress annotation?"