php - 在 PHP Try Catch block 中抛出异常

标签 php exception-handling drupal-6 try-catch

我在 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/

相关文章:

php - 使用 Painty 将 HTML 转为图像文件

PHP:包含在包含文件中

java - 在 Java 中捕获 Scala 中抛出的异常 - 无法访问的 catch block

javascript - 如何在 javascript 中迭代 this.value

php - 使用 PHP 调用特定服务的 SOAP 方法

PHP DRY 抛出 InvalidArgumentException

python - 获取导致异常的异常描述和堆栈跟踪,全部作为字符串

drupal-6 - Drupal 6 : Adding sub menu items on a menu item?

drupal-6 - 如何在 drupal 中设置 View 的寻呼机样式?

PHP - MYSQL - 避免计算重复元素