dongmi4720 2009-12-28 15:54
浏览 54
已采纳

如何捕获这个嵌套异常?

Example: I use a PDO method that throws an exception. But inside the try block, I also throw an own Exception if something else goes wrong. Now I want to handle the PDOException and my own Exception separately. How could I separate this to make it work?

   public function prepare(string $sql, array $params) {
    try {
        $prepared = $this->dbh->prepare($sql); // may throw PDOException
        $i = 1;
        foreach ($params as $param) {
        $ok = $prepared->bindParam($i, $param);
        if (!$ok) {
            throw new Exception("Unable to bind parameter (" . $param . ") to prepared statement: " . $sql);
        }
        $i++;
        }
    } catch (PDOException $e) {
        throw new Exception("DB:prepare(): Could not prepare statement. " . $e->getMessage());
    }
    return $prepared;
   }

Please note that I have a global error handler that takes care of logging any exception to a file. That's why I throw my own exceptions instead of writing directly to a log file (that way, I get also the backtrace).

  • 写回答

2条回答 默认 最新

  • duanpanzhu2910 2009-12-28 15:59
    关注

    You can use several catch blocks, like this :

    try {
        // ...
    } catch (PDOException $e) {
        // Handle the PDOException, with some specific code
    } catch (Exception $e) {
        // Handle any other kind of Exception 
        // that has not already been catched by 
        // one of the previous(es) catch block
    }
    

    But note you have to put the "most specific" exception type first -- which means Exception has to be the last one.


    Here are a couple of articles / blog-posts that might interest you, about exceptions and PHP :

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入