Podstawowe klasy PEAR (Previous) (Next) Using PEAR_Exception for advanced error handling in PHP 5+

View this page in Last updated: Mon, 02 Jul 2007
English | French | German | Japanese | Polish | Plain HTML

PEAR_Exception - PHP 5+

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.

Podstawowe klasy PEAR (Previous) (Next) Using PEAR_Exception for advanced error handling in PHP 5+

Download Documentation Last updated: Mon, 02 Jul 2007
Do you think that something on this page is wrong? Please file a bug report or add a note.
User Notes:
Note by: michele.manzato@bigfoot.com
There is a simple workaround for full PHP5 applications to convert "creating a PEAR_Error" to "throwing PEAR_Exception":

<?php
function PEAR_ErrorToPEAR_Exception($err)
{
    if (
$err->getCode()) {
        throw new 
PEAR_Exception($err->getMessage(), $err->getCode());
    }
    throw new 
PEAR_Exception($err->getMessage());
}
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK'PEAR_ErrorToPEAR_Exception');
?>


This way, each time a PEAR_Error is created in an old
PEAR package it is immediately converted and thrown as
a PEAR_Exception.

This is particularly useful for several old PEAR packages, and notably important ones such as MDB2, which still use PEAR_Error reporting and will continue to do so in order to maintain PHP4 compatibility.