首页 > 解决方案 > 如何在 PHP 中捕获类中的异常?

问题描述

我有一个包含许多函数的类,用于提交和从 MySql 数据库中选择数据。为了节省时间,我需要一个try-catch块来捕获类中的所有异常。
我在下面尝试了我的代码,但它不起作用,因为该try块给出了语法错误。

代码
class DB_FunctWeb {
    public $db;
//my try block starts
try {
    function __construct($conn) {
        $this->$db=$conn;
    }

    function __destruct() {

    }
    //....more functions....

} catch (Exception $e) {
    $errnumber = $db->errno;

    header("./creator.php");
    if ($errnumber === 1062) {
        insertInfo(" Duplicate entry please re-enter farm name.");
        // echo $e->getMessage();
    } else {
        insertInfo(" An error occurred. Items where not added.");
    }
} finally {
    closeconn($db);
    mysqli_report(MYSQLI_REPORT_OFF);
}
}

问题
如何在类中捕获异常?

标签: phpexceptiontry-catchphp-7

解决方案


您捕获了类的实例化对象,而不是类定义:

try {
   $dbweb = new DB_FunctWeb($conn);
}
catch (Exception $e)
{
 ...
}

推荐阅读