php - 如何在 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);
}
}
问题
如何在类中捕获异常?
解决方案
您捕获了类的实例化对象,而不是类定义:
try {
$dbweb = new DB_FunctWeb($conn);
}
catch (Exception $e)
{
...
}
推荐阅读
- sql - 如何有效地查询 SQLite 并在 2d 地图上创建表示大型数据集的热图?
- java - 当我只想更新一张地图时覆盖所有内部地图值
- java - 如何解码替换密码中的密钥?
- python - 多对多 - 管理页面中的数据过多
- javascript - 为什么在使用 useRef 时仍然使用旧的引用?
- c# - 试图让一个物体在地面上反弹一次 - 然后当它再次落下时穿过地面
- puppeteer - Puppeteer 中的 networkIdle0 事件是否仅限于页面?
- pytest - Visual Studio Code - 为 PyTest 指定 e -p no:faulthandler
- vue.js - 在 Vue 中链接静态 HTML 页面
- java - 尝试并捕获在 JAVA 中执行