0

私はphpでcatchを試すのが初めてで、それをいじっていました。

これを試してみると、うまくいきます

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 に答える