12

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?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Caner
  • 57,267
  • 35
  • 174
  • 180

3 Answers3

31

The throws declaration is part of the method contract. You should always be as precise as possible when defining contracts. Saying throws Exception is therefore a bad idea.

It's bad for the same reason it is bad practice to say a method returns an Object when it is guaranteed to return a String.

Furthermore, a caller of the method would necessarily have to catch Exception (unless he want to propagate this ugliness), and catching Exception is also a bad idea. See the answers to this question: Is it a bad practice to catch Throwable?

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
4

This forces everybody using this method to handle thrown Exceptions.

Even if you like using checked exceptions (which I don't) this leaves you with no information at all what kind of stuff might go wrong. So you can't really handle it in a meaningful way.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
0

Throws declaration means that: - something inside your method may produce such checked exception - your method is unable or unwilling to deal with it

You shall use most specific exception, and resist the temptation to group unrelated exceptions to reduce amount of throws declarations. If you feel, that there are too many of them, then your method is overcomplicated and shall be broken into smaller more manageabnle methods

Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35