In the past I\'d read tons of code with methods like:
public Object doSomething() throws Throwable {
...
}
Is it common practice to do
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
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.
The only use case I can think of would be for test code like unit tests. But Adam's counterpoint still stands "If so, then it's not good practice. It doesn't provide any useful information to class (method) user."