views:

133

answers:

4

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.

A: 

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.

Michael Borgwardt
+6  A: 

You can use Checkstyle eclipse plugin to do the same. Check 'IllegalCatch' section at documentation

Adi
Checkstyle is what you want. A reasonably simple to configure eclipse plugin which can report style problems in the code base as warnings or errors. Even better, hook it up with Hudson for a great Continuous Integration environment.
Chris Knight
+2  A: 

FindBugs can report this:

REC: Exception is caught when Exception is not thrown (REC_CATCH_EXCEPTION)

This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } 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 catches RuntimeException as well, masking potential bugs.

polygenelubricants
+3  A: 

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.

Stephen C