Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

java - Is "throws Exception" bad practice?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...