downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Referencias Explicadas> <Excepciones
Last updated: Fri, 20 May 2011

view this page in

Ampliar las Excepciones

Una clase de Excepción definida por el usuario puede ser definida ampliando la clase Exception interna. Los miembros y las propiedades de abajo muestran lo que es accesible dentro de la clase hija que deriva de la clase Exception interna.

Example #1 La clase Exception Interna

<?php
class Exception
{
    protected 
$message 'Unknown exception';   // mensaje de excepción
    
private   $string;                          // caché de __toString
    
protected $code 0;                        // código de excepción definido por el usuario
    
protected $file;                            // nombre de archivo fuente de la excepción
    
protected $line;                            // línea fuente de la excepción
    
private   $trace;                           // determinación del origen
    
private   $previous;                        // excepción previa si la excepción está anidada

    
public function __construct($message null$code 0Exception $previous null);

    final private function 
__clone();           // Inhibe la clonación de excepciones.

    
final public  function getMessage();        // mensaje de excepción
    
final public  function getCode();           // código de excepción
    
final public  function getFile();           // nombre de archivo fuente
    
final public  function getLine();           // línea fuente
    
final public  function getTrace();          // una matriz de backtrace()
    
final public  function getPrevious();       // excepción anterior
    
final public  function getTraceAsString();  // cadena formateada del seguimiento del origen

    /* Sobrescribible */
    
public function __toString();               // cadena formateada para mostrar
}
?>

Si una clase extiende la clase Exception interna y redefeine el constructor, se recomienda encarecidamente que también llame a parent::__construct() para asegurarse que toda la información disponible haya sido asignada apropiadamente. El método __toString() puede ser sobrescrito para proporcionar una salida personalizada cuando el objeto es presentado como una cadena.

Note:

Las excepciones no se pueden clonar. Intentar clonar una Excepción resultará en un error E_ERROR fatal.

Example #2 Extender la clase Exception (PHP 5.3.0+)

<?php
/**
 * Definir una clase de excepción personalizada
 */
class MiExcepción extends Exception
{
    
// Redefinir la excepción, por lo que el mensaje no es opcional
    
public function __construct($message$code 0Exception $previous null) {
        
// algo de código
    
        // asegúrese de que todo está asignado apropiadamente
        
parent::__construct($message$code$previous);
    }

    
// representación de cadena personalizada del objeto
    
public function __toString() {
        return 
__CLASS__ ": [{$this->code}]: {$this->message}\n";
    }

    public function 
funciónPersonalizada() {
        echo 
"Una función personalizada para este tipo de excepción\n";
    }
}


/**
 * Crear una clase para probar la excepción
 */
class ProbarExcepción
{
    public 
$var;

    const 
THROW_NONE    0;
    const 
THROW_CUSTOM  1;
    const 
THROW_DEFAULT 2;

    function 
__construct($avalue self::THROW_NONE) {

        switch (
$avalue) {
            case 
self::THROW_CUSTOM:
                
// lanzar la excepción personalizada
                
throw new MiExcepción('1 no es un parámetro válido'5);
                break;

            case 
self::THROW_DEFAULT:
                
// lanzar la predeterminada.
                
throw new Exception('2 no está permitido como parámetro'6);
                break;

            default: 
                
// No hay excepción, el objeto se creará.
                
$this->var $avalue;
                break;
        }
    }
}


// Ejemplo 1
try {
    
$o = new ProbarExcepción(ProbarExcepción::THROW_CUSTOM);
} catch (
MiExcepción $e) {      // Será atrapada
    
echo "Atrapada mi excepción\n"$e;
    
$e->funciónPersonalizada();
} catch (
Exception $e) {        // Skipped
    
echo "Atrapada la Excepción Predeterminada\n"$e;
}

// Continuar la ejecución
var_dump($o); // Null
echo "\n\n";


// Ejemplo 2
try {
    
$o = new ProbarExcepción(ProbarExcepción::THROW_DEFAULT);
} catch (
MiExcepción $e) {      // Este tipo no coincide
    
echo "Atrapada mi excepción\n"$e;
    
$e->funciónPersonalizada();
} catch (
Exception $e) {        // Will be caught
    
echo "Atrapada la Excepción Predeterminada\n"$e;
}

// Continuar la ejecución
var_dump($o); // Null
echo "\n\n";


// Ejemplo 3
try {
    
$o = new ProbarExcepción(ProbarExcepción::THROW_CUSTOM);
} catch (
Exception $e) {        // Será atrapada
    
echo "Atrapada la Excepción Predeterminada\n"$e;
}

// Continuar la ejecución
var_dump($o); // Null
echo "\n\n";


// Ejemplo 4
try {
    
$o = new ProbarExcepción();
} catch (
Exception $e) {        // Saltado, sin excepción
    
echo "Atrapada la Excepción Predeterminada\n"$e;
}

// Continuar la ejecución
var_dump($o); // ProbarExcepción
echo "\n\n";
?>

Note:

Las versiones de PHP 5, anteriores a PHP 5.3.0, no soportan excepciones anidadas. El siguiente fragmento de código se puede usar para reemplazar la clase MiExcepción si se desea ejecutar este ejemplo.

<?php
/**
 * Definir una clase de excepción personalizada
 */
class MiExcepción extends Exception
{
    
// Redefinir la excepción, por lo que el mensaje no es opcional
    
public function __construct($message$code 0) {
        
// algo de código
    
        // asegúrese de que todo está asignador apropiadamente
        
parent::__construct($message$code);
    }

    
// representación de cadena personalizada del objeto
    
public function __toString() {
        return 
__CLASS__ ": [{$this->code}]: {$this->message}\n";
    }

    public function 
funciónPersonalizada() {
        echo 
"Una función personalizada para este tipo de excepción\n";
    }
}
?>



Referencias Explicadas> <Excepciones
Last updated: Fri, 20 May 2011
 
add a note add a note User Contributed Notes Ampliar las Excepciones
joechrz at gmail dot com 18-Feb-2010 11:18
It's important to note some unexpected behavior when overriding the __toString method of an Exception.  The default PHP exception handler will truncate the result of the __toString method to the number of bytes specified by log_errors_max_len in php.ini. 

To get around this problem, you need to either change the value of log_errors_max_len:

<?php
   
// recommended: disable error logging
    // so the log files don't become bloated from huge
    // exception strings
   
ini_set('log_errors','off');

   
// log_errors_max_len = infinite length
   
ini_set("log_errors_max_len",0);
?>

or specify a custom exception handler:
<?php
   
function long_exception_handler($exception) {
       
// for compatibility, call __toString
       
echo $exception->__toString();
    }
   
set_exception_handler('long_exception_handler');
?>
iamhiddensomewhere at gmail dot com 31-Dec-2009 11:17
As previously noted exception linking was recently added (and what a god-send it is, it certainly makes layer abstraction (and, by association, exception tracking) easier).

Since <5.3 was lacking this useful feature I took some initiative and creating a custom exception class that all of my exceptions inherit from:

<?php

class SystemException extends Exception
{
    private
$previous;
   
    public function
__construct($message, $code = 0, Exception $previous = null)
    {
       
parent::__construct($message, $code);
       
        if (!
is_null($previous))
        {
           
$this -> previous = $previous;
        }
    }
   
    public function
getPrevious()
    {
        return
$this -> previous;
    }
}

?>

Hope you find it useful.
sapphirepaw.org 24-Nov-2009 03:37
Support for exception linking was added in PHP 5.3.0. The getPrevious() method and the $previous argument to the constructor are not available on any built-in exceptions in older versions of PHP.
paragdiwan at gmail dot com 17-Jan-2009 09:32
I have written similar simple custom exception class. Helpful for newbie.
<?php
   
/*
        This is written for overriding the exceptions.
        custom exception class
    */
   
error_reporting(E_ALL-E_NOTICE);
    class
myCustomException extends Exception
   
{
       
        public function
__construct($message, $code=0)
        {
           
parent::__construct($message,$code);
        }   

        public function
__toString()
        {
            return
"<b style='color:red'>".$this->message."</b>";
        }
       
       
    }

    class
testException
   
{
       
        public function
__construct($x)
        {
       
           
$this->x=$x;
           
        }
       
        function
see()
        {
           

            if(
$this->x==9 )
            {
                throw new
myCustomException("i didnt like it");
            }
        }
    }

   
$obj = new testException(9);
    try{
   
       
$obj->see();
    }
    catch(
myCustomException $e)
    {
        echo
$e;
    }
?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites