2012-09-13 65 views
0

我是新來嘗試抓住php,我正在玩它。PHP嘗試抓取異常它是如何工作的

當我嘗試這一個,它工作正常

try { 

    if (!$connect) 
    { 
     throw new Exception("it's not working"); 
    } 
} catch (Exception $e) { 
    $e->getMessage(); 
}   

當我嘗試這一個,這是行不通的

try {  
    if (!$connect) { 
     throw new MyException("it's not working"); 
    }  
} catch (MyException $e) { 
    echo $e->getMessage(); 
}  

我只是改變了異常的名稱,有人可以解釋我出錯的地方。 感謝

回答

4

爲了使用一個自定義異常,你需要擴展Exception類:

http://php.net/manual/en/language.exceptions.extending.php

/** 
* Define a custom exception class 
*/ 
class MyException extends Exception 
{ 
    // Redefine the exception so message isn't optional 
    public function __construct($message, $code = 0, Exception $previous = null) { 
     // some code 

     // make sure everything is assigned properly 
     parent::__construct($message, $code, $previous); 
    } 

    // custom string representation of object 
    public function __toString() { 
     return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; 
    } 

    public function customFunction() { 
     echo "A custom function for this type of exception\n"; 
    } 
} 
+0

感謝曼斯菲爾德 –

+0

@KhanqueredPro沒問題。如果它對您有幫助,請務必點擊複選標記將其標記爲答案。 – Mansfield