This is more of best practice question.
I'm working with old Java code at the moment. I'm seeing a lot of subclasses of Exception only overwrite the constructors. I'm not sure if there is any practical use of subclassing Exception like this. I think just calling the Exception constructor and pass in a message would be just as effective, and there wouldn't be many subclasses around. Code is liability.
The point of subclassing is that your code can distinguish different types of failure and treat them differently. If you just change the message, then a human can distinguish them in the logs, but that's all.
If the exceptions you are seeing are not actually handled differently, but just caught in a catch-all catch(Exception e) then perhaps someone was being over-enthusiastic with the subclasses, but it is often useful for cleanly separating layers of code and working out which classes should handle which kinds of problem.
For example, one type of exception may indicate a timeout, and it may be appropriate to retry after a short delay, whereas another type of exception indicates an unrecoverable failure (an invalid query, perhaps) which must be thrown up to a higher level or perhaps indicated to the user.
To add to the other answers:
If you extend Exception and throw it, you're declaring a new checked exception. It will have to be declared on the throws clause of your method. You are saying to the caller: "Here is a unusual case which you must code for".
I think checked exceptions are over-used. They are only really useful in situations where the caller can expect to recover from the problem. The vast majority of exceptions I have seen are the kind that the caller cannot reasonably expect to recover from. In this case you should use a RuntimeException descendant such as IllegalStateException or IllegalArgumentException and let top-level error handling take care of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With