I'm trying to encourage a best practice of not catching general exceptions in Java code. eg:
try {
...
} catch (Exception e) { // bad!
...
}
Is there a way to flag this as an error/warning in Eclipse?
I know PMD picks this up, but I'd rather avoid integrating it into everyone's build environment at the moment.
You can use Checkstyle eclipse plugin to do the same. Check 'IllegalCatch' section at documentation
FindBugs
can report this:
REC
:Exception
is caught whenException
is not thrown (REC_CATCH_EXCEPTION
)This method uses a
try-catch
block that catchesException
objects, butException
is not thrown within thetry
block, andRuntimeException
is not explicitly caught. It is a common bug pattern to saytry { ... } catch (Exception e) { something }
as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catchesRuntimeException
as well, masking potential bugs.
Running the FindBugs, CheckStyle or PMD on every build would slow everyone's builds down, and I imagine that is why you are looking at the Eclipse approach. Unfortunately, that may also be problematic, depending on availability (and robustness) of plugins. Plus, you'll still take a performance hit in incremental and (especially) full project builds.
Another alternative would be to set up a Hudson continuous integration server and configure it to run style checkers, coverage tools and so on, tracking the results over time using the Sonar plugin.
As far as I can tell, it's not in the list at Window -> Preferences -> Java -> Compiler -> Errors/Warnings, and thus not possible - unless you fancy writing your own ecliple plugin.
来源:https://stackoverflow.com/questions/2666057/is-there-a-way-to-make-eclipse-report-a-general-catch-exception-e-as-an-erro