PEAR_Exception is the recommended error handling solution for PHP 5-based packages in PEAR. PEAR_Exception is a lightweight wrapper above the built-in Exception class in PHP 5 that provides the ability to specify causes for errors, register observers, and many more features.
Example usage (demonstration only, not recommended practice):
<?php
require_once 'PEAR/Exception.php';
class MyPackage_Exception extends PEAR_Exception {}
try {
throw new PEAR_Exception('exception 1');
} catch (MyPackage_Exception $e) {
echo 'this is not executed';
} catch (PEAR_Exception $e) {
echo 'this is executed';
}
try {
throw new MyPackage_Exception('exception 2');
} catch (MyPackage_Exception $e) {
echo 'this is executed';
} catch (PEAR_Exception $e) {
echo 'this is not executed';
}
?> |
Exceptions in general should be used only for exceptional circumstances - for error conditions that require termination of execution. PEAR_Exception should mainly be used for transmitting error information outside the existing package, and not for normal flow control. Use Control Structures in favor of exceptions wherever possible.