Is “throws Throwable” good practice

前端 未结 9 1087
攒了一身酷
攒了一身酷 2020-12-30 21:14

In the past I\'d read tons of code with methods like:

public Object doSomething() throws Throwable {
    ...
}

Is it common practice to do

9条回答
  •  难免孤独
    2020-12-30 21:42

    You should not throw Throwable. Here's why.

    Throwable is the top of the hierarchy of things that can be thrown and is made up of Exceptions and Errors. Since Errors by definition arise from unsalvagable conditions, it is pointless to include them in your method declaration. That leaves just Exception.

    You should declare your method with throws Exception instead.


    Note that the narrower the range of throws the better.

    Declaring your method to be throws Exception is ok if your method doesn't generate the exceptions, but instead calls other code that is declared as throws Exception and you want exceptions to percolate up the call stack.

    If your method is the generating the exception, then declare a narrower range, eg throws IOException, MyProcessingException, etc

提交回复
热议问题