PHP尝试在异常处理中捕获

时间:2014-10-11 01:21:01

标签: php exception-handling

我有一个数据库类dbconnect.php和processform.php。在dbconnect.php中,有一种连接数据库的方法。

如果出现错误,我该如何抛出异常?我在哪里把try catch块放在processform.php中?人们说我不应该直接在课堂内回应错误。这是一个例子:

    <?php

    // dbconnect.php

    class DbConnect
    {

        public function open_connection()
        {

            /* Should I do it like this? */
            $this->conn = PDO($dsn, $this->username, $this->password);
            if (!$this->conn) {
                throw new Exception('Error connecting to the database.');
            }

            /* Or like this */
            try {
                $this->conn = PDO($dsn, $this->username, $this->password);
            } catch (PDOException $e) {
                echo 'Error: ', $e->getMessage(), '<br>';
            }
       }
    ?>

    // processform.php

    <?php
        require_once 'dbconnect.php';
        $pdo = new DbConnect($host, $username, $password);
        try {
            $pdo->open_connection();
        } catch (PDOException $e) {
            echo 'Error connecting to the database.');
        }
    ?>

我真的想学习在我的代码中实现try catch的正确方法。

2 个答案:

答案 0 :(得分:1)

您不必手动抛出异常,尤其是在成功连接时: - )

相反,您需要告诉PDO,当出现问题时需要抛出异常,并且在打开数据库连接时可以这样做:

$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->conn = new PDO($dsn, $this->username, $this->password, $options);

现在您可以将所有内容放在try / catch块中,但这甚至不是必需的;如果你不这样做,当你不手动捕获它们时,php会向你显示unhandled exceptions完成堆栈跟踪。

当您决定要为访问者微调错误处理时,可以使用set_exception_handler()设置自己的异常处理程序。这样您就可以在一个地方处理所有内容,而不是在try / catch块中包含不同的部分。你当然应该喜欢它吗?

答案 1 :(得分:0)

在我的练习中,我更喜欢在底部捕获异常。我的意思是,你的DbConnect的第二种方式。

您可以将错误消息输出到错误日志。并将错误代码返回给前端。因此,前端知道如何以友好的方式告诉用户错误。

此外,您可以使用全局错误处理程序(例如set_error_handler / set_exception_handler)来执行此操作。发生错误时重定向到错误页面。

相关问题