Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to have specific Exceptions for everything? Or is it better to reuse a bit more abstract exception?

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.

like image 920
raspayu Avatar asked Oct 19 '10 06:10

raspayu


1 Answers

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.

like image 179
Stephen C Avatar answered Sep 20 '22 23:09

Stephen C