I am dealing with a project, in wich I have written one Exception for each possible exception situation. The point is that I find it more “readable”, but I am getting an insane amount of different exceptions.
Is it considered a good practice to do it like that? Or should I write just exceptions a bit more abstract, in order to have not so many?
Thanks a lot for your time.
Which is better depends on the likelihood that your code is going to catch the specific exceptions. If you are only ever likely to catch (or discriminate in some other way) the more general (superclass) exceptions, then having lots of more specific (subclass) exceptions doesn’t achieve much. In that case, it is probably better to define fewer exceptions and use exception messages to express the finer details of what has gone wrong.
On the other hand, if specific exceptions already exist, it makes sense to use them. Just throwing
java.lang.Exceptionorjava.lang.RuntimeExceptionis plain lazy, IMO.FOLLOW UP
If your code frequently looks like this:
… then your fine grained exceptions are not helping. But if it looks like this:
… then maybe your fine-grained exceptions are working for you. And if you declare these three exceptions as subclasses of
DatabaseDataException, then you can handle the cases together or separately as the circumstances dictate.Really, it is up to you to make your own judgement, in the context of your application.