Is “throws Throwable” good practice

前端 未结 9 1088
攒了一身酷
攒了一身酷 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:44

    It is really debatable matter. Having method throwing too many exceptions will result in lot of error handling code. Some times it is not intended.

    But because I don't like too many exception in signature does not mean that Lets use Parent of all exceptions and we are done!! It will not work.

    What one can do is categorise exceptions such as BusinessException,ServiceException so that if you have a business rule which says that minimum balance in account can not be less than say 100$ then InsufficientBalance exception will be generated which will be child of BusinessException

    so you method will be like

    public Object doSomething() throws BusinessException {
    
     if(!hasMinimumbalance())
      { 
        throw new InsufficientBalance(ErrorCode);
      }
    }
    

    What this will do is club related exceptions together and whenever API user wants to detect exception specific error then he can do it, else generic error handling is possible.

    The core point here is on the UI you should display to the user that You have run out of balance and you can not withdraw money

    You can say on the larger aspect to display human readable form of error it is really necessary to have separation of exceptions.

提交回复
热议问题