Monday, March 3, 2008

Musings About Exceptions and Errors

What's the semantic difference between triggering an error or throwing an exception. Seems like a clear cut difference, doesn't it?

But it really isn't all that crystal clear, I've noticed. Just search on Google with "exception vs error" and you get a lot of hits, and while many go on what marvelous things you can do with try-catch-finally blocks, not many (at least of those I looked into) go into great lengths of actually describing their difference. Some pages seem to want to answer the question, but lose themselves in the middle of thing, and veer of talking about something completely different. It seems like it isn't too clear for many programmers.

As a concrete example, LightFrame's database connection. You create a SQL object, which establishes a connection to the RDBMS you have defined in the settings. Let's assume that the connection fails. Should the object trigger an error, or should it throw an exception? If you prefer to catch an exception, what do you plan on doing with that exception? Correct your settings in run-time? I know you have an objection already, but bear with me...

LightFrame is currently set up with custom exception and error handlers. If an error occurs, or an exception is uncaught, a 500 HTTP response code is given, with an accompanying message and a backtrace of function/method calls. So, an uncaught exception is, for all practical purposes just a glorified error.

As I already saw in some of Google's results, there IS a difference between errors and exceptions in PHP that is non-trivial, and they should be treated that way. It is meaningful to use both, and overusing exceptions is something that shouldn't taken lightly. A good differentiation between errors and exceptions is that errors occurs when the shit has hit the fan, and you are pretty much screwed - die and get it over with - while exceptions are events where something has gone wrong, but there's something that could be done to remedy the situation, often, trying the same thing from a different approach.

To get back to the database example above, a connection error would do good to throw an exception. When the exception is caught, one could inform the database administrator about the problem via, say, email. In some cases, the data that was about to be gathered from the database isn't all that crucial and can be disregarded occasionally, or replaced with something generic. As a counter-example, an error should be preferred if there is actually something totally wrong. For example, if you try to use "excel" as a database backend, LightFrame will not try to fix that on run-time with an exception. It's a clear cut case: Excel isn't supported, your configs are wrong.

One must wonder whether these musings bite me in the ass someday...

No comments: