I’m reviewing code for a colleague and I encounter a piece of code similar to this:
public X Foo1(Y y) throws Exception {
X result = new X(y);
result.Foo2();
return result;
}
I believe there is no need for throws Exception part but I’m having difficulties justifying this. It might make sense if it was more specific Exception(FileNotFound, NoMemory etc.) but as it is I think it is unnecessary. Can someone give me some reasons what problems this can cause and why it is bad practice? Or is this code ok?
The
throwsdeclaration is part of the method contract. You should always be as precise as possible when defining contracts. Sayingthrows Exceptionis therefore a bad idea.It’s bad for the same reason it is bad practice to say a method returns an
Objectwhen it is guaranteed to return aString.Furthermore, a caller of the method would necessarily have to catch
Exception(unless he want to propagate this ugliness), and catchingExceptionis also a bad idea. See the answers to this question: Is it a bad practice to catch Throwable?