Exceptions

Last modified: October 20, 2009 - 03:28

Basic conventions

  1. As Exceptions are classes, they should follow all coding standards for object-oriented code like any other class.
  2. All Exceptions must end with the suffix "Exception".
  3. All Exceptions must include an appropriate translated string as a message, unless the Exception is thrown very early in the bootstrap process before the translation system is available. That is extremely rare.
  4. Exception classes should be named for the subsystem to which they relate, and the type of error. That is, [Subsystem][ErrorType]Exception.

The use of subclassed Exceptions is preferred over reusing a single generic exception class with different error messages as different classes may then be caught separately.

Example:

<?php
class WidgetNotFoundException extends Exception {}

function
use_widget($widget_name) {
 
$widget = find_widget($widget_name);

  if (!
$widget) {
    throw new
WidgetNotFoundException(t('Widget %widget not found.', array('%widget' => $widget_name)));
  }
}
?>

Try-catch blocks

try-catch blocks should follow a similar line-breaking pattern to if-else statements, with each catch statement beginning a new line.

Example:

<?php
try {
 
$widget = 'thingie';
 
$result = use_widget($widget);

 
// Continue processing the $result.
  // If an exception is thrown by use_widget(), this code never gets called.
}
catch (
WidgetNotFoundException $e) {
 
// Error handling specific to the absence of a widget.
}
catch (
Exception $e) {
 
// Generic exception handling if something else gets thrown.
 
watchdog('widget', $e->getMessage(), WATCHDOG_ERROR);
}
?>

Inheritance

PHP requires that all exceptions inherit off of the Exception class, either directly or indirectly.

When creating a new exception class, it should be named according to the subystem they relate to and the error message they involve. If a given subsystem includes multiple exceptions, they should all extend from a common base exception. That allows for multiple catch blocks as necessary.

<?php
class FelineException extends Exception {}

class
FelineHairBallException extends FelineException {}

class
FelineKittenTooCuteException extends FelineException {}

try {
 
$nermal = new Kitten();
 
$nermal->playWith($string);
}
catch (
FelineHairBallException $e) {
 
// Do error handling here.
}
catch (
FelineKittenTooCuteException $e) {
 
// Do different error handling here.
}
catch (
FelineException $e) {
 
// Do generic error handling here.
}
// Optionally also catch Exception so that all exceptions stop here instead of propagating up.
?>

 
 

Drupal is a registered trademark of Dries Buytaert.