Is “throws Exception” bad practice?

前端 未结 3 1136
后悔当初
后悔当初 2020-12-19 02:02

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);
    resul         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-19 02:42

    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?

提交回复
热议问题