我是新手尝试在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();
}
我只更改了例外的名称,有人可以解释我哪里出错了。 感谢
答案 0 :(得分: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";
}
}