2010-04-09 12 views
11

di costruzione per le eccezioni di PHP ha terzo parametro, documentation dice:Come implementare eccezione concatenamento in PHP

$previous: The previous exception used for the exception chaining. 

ma non riesco a farlo funzionare. Il mio codice è simile al seguente:

try 
{ 
    throw new Exception('Exception 1', 1001); 
} 
catch (Exception $ex) 
{ 
    throw new Exception('Exception 2', 1002, $ex); 
} 

mi aspetto Eccezione 2 per essere gettato e mi aspetto che avrà Eccezione 1 allegata. Ma tutto quello che ottengo è:

Fatal error: Wrong parameters for Exception([string $exception [, long $code ]]) in ... 

Cosa sto facendo male?

+2

Qual è la versione di PHP? – EFraim

risposta

20

Il terzo parametro richiede la versione 5.3.0.

1

ottengo:

Uncaught exception 'Exception' with message 'Exception 1' ... 

Next exception 'Exception' with message 'Exception 2' in ... 

È usando PHP> 5.3?

1

Prima di 5.3 è possibile creare la propria classe di eccezioni personalizzata. Si consiglia anche di fare questo, voglio dire se io catch (Exception $e) allora il mio codice deve gestire tutte le eccezioni piuttosto che solo quello che voglio, il codice lo spiega meglio.


    class MyException extends Exception 
    { 
    protected $PreviousException; 

    public function __construct($message, $code = null, $previousException = null) 
    { 
     parent::__construct($message, $code); 
     $this->PreviousException = $previousException; 
    } 
    } 

    class IOException extends MyException { } 

    try 
    { 
    $fh = @fopen("bash.txt", "w"); 
    if ($fh === false) 
     throw new IOException('File open failed for file `bash.txt`'); 
    } 
    catch (IOException $e) 
    { 
    // Only responsible for I/O related errors 
    }