0

我是新来尝试在 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

1 回答 1

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";
    }
}
于 2012-09-13T18:24:00.117 回答