Why exceptions rock
A lot of people dislike exceptions because
- try-catch blocks are ugly
- some languages will force you to deal with them
But when you consider the alternatives, exceptions are great.
Let me show you why
A typical php scenario is a user filling out a form to create a new row in a database. Examples where this happens are an admin creating a user account or a customer placing an order. Now the code closest to the GUI will check the fields superficially (are they filled in? Does the data have the right type?) and might alter the data somewhat (whitespace removal, htmlspecialchars) before passing it on to deeper levels of code, eventually reaching the database:
But what happens if DB insertion fails? The database, often a product of a team of developers working for decades, is bound to have some stricter error checks than your initial GUI class and so chances are quite high that things might go wrong. Other errors might occur somewhere in the little blue cloud if the data is interpreted and turns out to make very little sense (a sum isn't right, a url can't be parsed etc).
The advantage of exceptions is that an exception thrown at any point in this chain will bubble up through the call stack, until it reaches a point where it can be dealt with. If not, it'll arrive at the GUI class, which can read out its message and inform the user what went wrong.
Consider doing the same with special return values: using functions that return either the expected output or some codeword like 'false' or 'null' or '-1'. In this scenario every function along the way needs to check its input, and if it can't deal with it return a codeword of its own. Apart from the messiness of converting between false and null and using the === operator this scenario forces secure code to wrap if statements around nearly all functions, and leaves security holes whenever the programmer forgets. With exceptions code execution is terminated immediatly and the exception is passed up the call stack without any additional lines of code.
None of this is new, or surprising, but its just so strange to see a big language like php get things so wrong...
Notes...
- To avoid dealing with errors (php4) and exceptions (php5) simultaneously you can define a custom error handler that converts errors into exceptions.
- To create the errors as close to the GUI as possible it is always a good idea to define any objects made from user data as soon as possible. Since php allows type hinting for objects this saves you a great deal of checking function input. This email address class was created for just that reason
May 24th, 2009
Comments
No comments yet! Feel free to post some using the form below.
If you wish to add code to your comment you can use code tags, like this: <code class="php">yourCodeHere</code>.
Quite a large number of languages are supported, although I can't guarantee it'll be pretty. Inside the code tags you can use any characters except for the string "</code>".