duanmi4379 2011-01-19 09:12
浏览 96
已采纳

php自定义异常处理

I am wanting to handle exceptions in my PHP application myself.

When I throw an exception I am wanting to pass along a title to be used in the error page.

Can someone please link me to a good tutorial, or write a clear explanation of how the exception handling actually works (eg how to know what sort of exception you are dealing with, etc.

  • 写回答

4条回答 默认 最新

  • douwei1408 2011-01-19 09:19
    关注

    Official docs is a good place to start - http://php.net/manual/en/language.exceptions.php.

    If it is just a message that you want to capture you would do it at follows;

    try{
        throw new Exception("This is your error message");
    }catch(Exception $e){
        print $e->getMessage();
    }
    

    If you want to capture specific errors you would use:

    try{
        throw new SQLException("SQL error message");
    }catch(SQLException $e){
        print "SQL Error: ".$e->getMessage();
    }catch(Exception $e){
        print "Error: ".$e->getMessage();
    }
    

    For the record - you'd need to define SQLException. This can be done as simply as:

    class SQLException extends Exception{
    
    }
    

    For a title and message you would extend the Exception class:

    class CustomException extends Exception{
    
        protected $title;
    
        public function __construct($title, $message, $code = 0, Exception $previous = null) {
    
            $this->title = $title;
    
            parent::__construct($message, $code, $previous);
    
        }
    
        public function getTitle(){
            return $this->title;
        }
    
    }
    

    You could invoke this using :

    try{
        throw new CustomException("My Title", "My error message");
    }catch(CustomException $e){
        print $e->getTitle()."<br />".$e->getMessage();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 使用yolov5-7.0目标检测报错
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备