Why Exception Handling Matters

As I start working on PHP 5 projects in my own time (and pushing for the upgrade of our sites to PHP 5 at work) I'm gaining more exposure to the newer features of PHP 5. The big one for me is the try-catch-throw exception handling abilities. When I think of my old job and the problems we faced with exception handling it makes me wish that we could've written it in PHP 5.

Anyhow I've been working with my friend Derek Martin on a component for the Zend Framework to provide support for using Last.fm via Audioscrobller's REST web services.

Since the ZF is PHP 5 only it was time to break out the try-catch-throw. Check out how simple this can be:

  2. protected function _getInfoByUser($service)
  3. {
  4.         $service = (string) $service;
  6.         try {
  7.                 $response = $this->_rest->restGet("/1.0/user/{$this->user}/{$service}");
  9.                 if ($response->isSuccessful()) {
  10.                         $profile_info = simplexml_load_string($response->getBody());
  11.                         return $profile_info;
  12.                 } else {
  14.                         if ($response->getBody() == "No such user") {
  15.                                 throw new Zend_Service_Exception('Could not find the user ' . $this->user);
  16.                         } else {
  17.                                 throw new Zend_Service_Exception('The REST service ' . $service . ' returned the following status code: ' . $response->getStatus());
  18.                         }
  20.                 }
  22.         } catch (Zend_Service_Exception $e) {
  23.                 throw ($e);
  24.         }
  26. }

So, if there are any errors generated I "throw" an exception that the framework can handle. I then "catch" that exception and "throw" it up another level, where the controller (which is calling the above code in question) catches the exception I originally created. Nice and easy. Thanks to Amy Hoy for giving me a 60 second clinic on try-catch-throw via IM yesterday.

Next week has been decleared "Proposals Week" on the Zend Framework mailing list, so Derek and I are trying to get our contribution together so that we can submit it next week. Last.fm and Audioscrobbler are a neat technology that I use all the time to track my own musical tastes and find things that I like. Hopefully the other users like it enough that it gets accepted.