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.Exception
or java.lang.RuntimeException
is plain lazy, IMO.
FOLLOW UP
Well, I am catching always specific exceptions, but the thing is that, in other "catches" I use also specific exceptions that are kind of similar (they can refer to "database" for example, but they are not same). So the question is if it should be a good thing do a "DatabaseException", and use it, instead of "DatabaseConnectionException" and "DatabaseDataException" for example, wich is more readable, but at the end i got millions of explicit exceptions.
If your code frequently 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 are not helping. 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 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.