2010-04-09 12 views
11

Konstruktor wyjątku PHP ma trzeci parametr, documentation mówi:Jak wdrożyć wyjątku łańcuchowym w PHP

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

Ale nie mogę tego dokonać. Mój kod wygląda następująco:

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

Spodziewam Wyjątek 2 do rzucania i spodziewam się, że będzie miał Wyjątek 1 załączeniu. Ale dostaję tylko:

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

Co robię źle?

+2

Jaka jest twoja wersja PHP? – EFraim

Odpowiedz

1

uzyskać:

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

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

używasz PHP> 5.3?

1

Przed 5.3 można po prostu utworzyć własną niestandardową klasę wyjątków. Jest to również zalecane, aby to zrobić, to znaczy, jeśli I catch (Exception $e) to mój kod musi obsłużyć wszystkie wyjątki, a nie tylko ten, który chcę, kod wyjaśnia to lepiej.


    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 
    }