dongxu7408 2012-09-13 18:22
浏览 36
已采纳

PHP Try Catch Exceptions如何工作

I'm new to try catch in php, and I was playing around with it.

when I try this one, it works fine

try {

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

When I try this one, it doesn't work

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

I have only changed the name of the exception, can someone explain where I went wrong pls. thanks

  • 写回答

1条回答 默认 最新

  • douhui3330 2012-09-13 18:24
    关注

    In order to use a custom exception, you need to extend the Exception class:

    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}
    ";
        }
    
        public function customFunction() {
            echo "A custom function for this type of exception
    ";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作