从类内部捕获异常

时间:2018-08-13 15:57:55

标签: php try-catch

我对尝试捕获概念有些困惑。 我在PHP中有这段代码。

<?php
while (true) {
    try {
        foreach ($data as $message) {
            $functionToCall = new functions();
            $functionToCall->remove($data);
        }
    } catch (Exception $e) {
        echo "This is inside catch";
        echo 'Message: ' . $e->getMessage();
    }
}

class functions
{
    public function __construct()
    {
        $this->dbConnection = pg_pconnect("host = $hostname port=$port dbname = $database user = $username password = $password") 
                    or die("Can't connect to database" . pg_last_error());
    }

    public function remove($data)
    {
        $query = "UPDATE table
        SET  isDeleted = true;
        $res = pg_query($this->dbConnection, $query);
        if (!$res) {
            print_r(error_get_last());
            throw new Exception(error_get_last(), 1);
        }
    }

}

我对代码进行了少许更改以引发我添加的异常

unset($this->dbconnection);

之后

 $query = "UPDATE table
    SET  isDeleted = true;

引发异常。引发了异常,但是我的捕获未捕获此异常。 如何捕获此错误? 谢谢

1 个答案:

答案 0 :(得分:0)

如果这是实际的代码,则看起来像语法问题,请尝试以下编辑:

public function remove($data)
    {
        $query = "UPDATE table SET 'isDeleted'= true";
        $res = pg_query($this->dbConnection, $query);
        if (!$res) {
            print_r(error_get_last());
            throw new Exception(error_get_last(), 1);
        }
    }

请注意引号周围的变化:$ query =“ UPDATE table SET'isDeleted'= true”;

您的异常逻辑似乎被解析为字符串。

请注意,您的代码未关闭$ query上的字符串...

 $query = "UPDATE table
        SET  \"isDeleted\" = true;
        $res = pg_query($this->dbConnection, $query);
        if (!$res) {
            print_r(error_get_last());
            throw new Exception(error_get_last(), 1);
        }