The more precise rethrow allows to write code that throws the exception really thrown :
public void foo(String bar) throws FirstException, SecondException {
try{
// Code that may throw both FirstException and SecondException
}
catch (Exception e){
throw e;
}
}
Prior to Java 7 you had to write :
public void foo(String bar) throws Exception {
try{
// Code that may throw both FirstException and SecondException
}
catch (Exception e){
throw e;
}
}
My question: is there a tool that allows to detect imprecise throw in order to replace "Exception
" with "FirstException, SecondException
"?
So far, I have checked that there is no compiler warning in Eclipse. There is no rule in FindBugs or CodePro.
I think this is not a situation for a compiler warning, because the "overly broad" exception is not necessarily a problem: Unless the method is final or private, it defines what kind of exception any subclass implementation can throw. In that case, the wide scope may have been intentional.
Your question would apply equally well for Java pre-7:
Here,
throws Exception
could also be considered bad practice (but there are no warnings about it).Along the same line of argument, note that you will get a compile error when you try to catch a (checked) Exception that cannot possibly be thrown, but you can add to the
throws
clause of the method signature all kinds of exceptions that the implementation body does not use.A tool like FindBugs would be useful though.
Update: "Unless the method is final or private" : I have to agree that for private or final methods (and maybe static ones, too) there could be a warning.
Update 2: Even for final methods, you may want to leave your options open to throw more Exceptions in the future without breaking the interface.