Exceptions

I see on a lot of projects stuff like this:

function getStuff()
{
  try
  {
    return $this->retrieveStuff()
  }
  catch (Exception $e)
  {
    return null;
  }
}

The issue, in this example, is not that we silence an error. It should be logged, but there could be a legitimate use for this. For instance, it requires a connection to a remote server we have no control over, and we still want to serve the rest of the content to the user, as the information is not vital.

No, my issue it that we catch all errors, when the aim was to catch only one error (for instance “unable to connect to that remote server”). Imagine now there is a real bug in retrieveStuff(), it would still be interpreted by developers as a connection errors.

The solution is to have one exception type per error type (it sounds obvious said that way, doesn’t it?), and only catch the specific error, for instance ConnectionError.

PHP’s error handling is historically bad, and even though new features use exceptions, the legacy ones don’t. Or sometimes functions should trigger a fatal error but it is only a warning, and the code continues, which can trigger unwanted and hard-to-debug results. There are amazing plugins for Symfony that convert errors to exceptions (and warnings seem to be handled properly, i.e. they are logged and don’t cause the page to fail). It’s a start.

However, even when you get exceptions, you can’t always filter them easily. For instance, in Symfony, there are many different errors that would throw the same class. Symfony has a handful of exceptions, Doctrine has a bit more (though they can be quite meaningless!). Overall, there are defined “by module” than “by error”.

Comparatively, Python’s handling of exceptions is exceptional1. There are exceptions for everything, and most of the time errors are handled by only checking the class and not the contents of the exception. It is probably the feature I love the most about Python. With the else, finally, and with statements, it is almost a pleasure to handle errors.

  1. sorry []
This entry was posted in PHP, Python, Symfony. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*
*