2011-12-11 60 views
-4

我有一個封裝PHP異常抽象類:PHP異常的自定義消息

abstract class MyException extends Exception 
{ 

    public function __construct($message, $code = 0, Exception $previous = null) 
    { 
     parent::__construct($message, (int) $code, $previous); 
    } 
} 

然後,我有其他類,如:

class UserException extends MyException 
{ 
    public function __toString() 
    { 
     return parent::getMessage(); 
    } 
} 

當試圖拋出一個錯誤做throw new UserException('User does not exist');

它不僅顯示我定義的消息。它顯示:

Fatal error: Uncaught User does not exist thrown in \path\ClassTest.php on line 69

如何擺脫「致命錯誤:未捕獲...」部分?

非常感謝。

編輯:

我已經找到了答案,用set_exception_handler()將覆蓋捕獲的異常。並允許提供回調函數

+0

您發佈的代碼幾乎無關緊要。你包括嘗試和捕捉?閱讀更多[這裏](http://www.w3schools.com/php/php_exception.asp)。另外,谷歌錯誤消息。 – Griffin

+1

你有沒有嘗試/抓住你需要的部分? – craniumonempty

+0

你是_throwing_而不是_catching_,所以它是_uncaught _... – Xaerxess

回答

0

「致命錯誤」部分是由於異常在try-catch語句之外被拋出並最終被php錯誤處理程序捕獲而生成的。未捕獲的異常總是致命的。

周圍嘗試與像try-catch語句產生異常的代碼:

try{ 
    $foo->bar(); 
catch(UserException $ex){ 
    // Do something with the exception. 
} 

或者你可以把自己的錯誤處理 - >Linky

但try-catch方法是「正確」的方法。