簡體   English   中英

PHP Try Catch Exceptions如何工作

[英]PHP Try Catch Exceptions how does it work

我是嘗試使用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();
}       

我只更改了異常的名稱,有人可以解釋我哪里出錯了。 謝謝

為了使用自定義異常,您需要擴展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";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM