问题
I have a runtime exception that I have created in my project, and I want to make sure that it is caught in one of my classes, so that the whole program doesn't explode when it occurs (i.e. if anyone deletes the try/catch statement I want to know by having something in the build or static analysis tools fail). Unfortunately, as java doesn't enforce me to have the try/catch statement for this unchecked exception, there is no way to enforce it on compile time. (I cannot change my exception to be a checked exception).
I am wondering if there is any way to enforce a try/catch statement in a specific class, probably with the use of the checkstyle/pmd/findbugs custom rules. (check that a specific method in a specific class has a try catch statement for my runtime exception).
Thanks.
回答1:
There is no existing detector in Checkstyle, FindBugs, or PMD (or their contributing packages) that does what you want. So you will have to roll your own.
The easiest way to solve this without actual programming would be to write a PMD XPath rule which looks for a method X
in a class Y
and a catch
block that catches your runtime exception underneath that.
Failing that, a custom Checkstyle check would be the next easiest, but it requires a small bit of programming and you will have to subsequently deploy your custom check everywhere.
You could also write your own FindBugs detector as suggested in another answer, but since you would not be using any specific FindBugs features (such as byte code analysis), it seems like overkill to me.
回答2:
The idea of runtime exceptions is that you don't need to specify a "throws XYException" clause.
You may however check findbugs-contrib. If that doesn't solve it you may write your own custom bug detector. Here are some starting points:
- http://www.cs.ubc.ca/~kdvolder/CPSC511/submissions_06_07/jerry.pdf
- http://www.ibm.com/developerworks/java/library/j-findbug1/
- http://www.ibm.com/developerworks/library/j-findbug2/
- http://www.danielschneller.com/search/label/findbugs
- http://tech.joshuacummings.com/2010/05/testing-custom-findbugs-detectors-in.html
- http://www.slideshare.net/rewbs/custom-findbugsdetectors
来源:https://stackoverflow.com/questions/26138487/static-analysis-custom-rule-to-enforce-unchecked-exception-handling