It better depends on the likelihood that your code will catch certain exceptions. If you can only ever catch (or distinguish in some other way) more general (superclasses) exceptions, then having a lot of more specific (subclasses) exceptions does not achieve much. In this case, it is probably better to identify fewer exceptions and use exception messages to express more subtle details of what went wrong.
On the other hand, if specific exceptions already exist, it makes sense to use them. Just throwing java.lang.Exception or java.lang.RuntimeException is lazy, IMO.
FOLLOW UP
Well, I always find special exceptions, but the fact is that in other "catches" I also use certain exceptions that are similar (for example, they can refer to the "database", but they are not the same), so the question is that it would be nice to throw a "DatabaseException" and use it instead of "DatabaseConnectionException" and "DatabaseDataException", for example, more readable, but in the end I got millions of explicit exceptions.
If your code often looks like this:
try { ... } catch (DatabaseConnectionException ex) { // do something } catch (DatabaseDataException ex) { // do same thing } catch (DatabaseTangoException ex) { // do same thing }
... then your fine-grained exceptions do not help. But if it looks like this:
try { ... } catch (DatabaseConnectionException ex) { // do something } catch (DatabaseDataException ex) { // do something completely different } catch (DatabaseTangoException ex) { // do something totally extraordinary }
... then maybe your minor exceptions will work for you. And if you declare these three exceptions as subclasses of DatabaseDataException , then you can handle cases together or separately, as circumstances require.
In fact, you decide what to do in the context of your application.
Stephen c
source share