我在 Drupal 6 .module 文件中有一个 PHP 函数。我正在尝试在执行更密集的任务(例如数据库查询)之前运行初始变量验证。在 C# 中,我曾经在 Try block 的开头实现 IF 语句,如果验证失败,则会引发新的异常。抛出的异常将在 Catch block 中捕获。以下是我的 PHP 代码:
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
throw $e->getMessage();
}
}
但是,当我尝试运行代码时,它告诉我只能在 Catch block 内抛出对象。
提前致谢!
最佳答案
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
关于php - 在 PHP Try Catch block 中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9041173/