在PHP Try-Catch块中引发异常


Throwing exceptions in a PHP Try Catch block

我在Drupal6.module文件中有一个PHP函数。我试图在执行更密集的任务(如数据库查询)之前运行初始变量验证。在C#中,我曾经在Try块的开头实现IF语句,如果验证失败,它会引发新的异常。抛出的异常将在Catch块中捕获。以下是我的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块中抛出。

请注意,这个特定的代码示例毫无意义,因为您可以简单地删除try-catch并获得相同的结果:

function _modulename_getData($field, $table) {
    if (empty($field)) {
      throw new Exception("The field is undefined."); 
    }
    // rest of code here...
}

所以异常将被抛出,并且可以在其他地方被捕获或处理。

如果您要编写一些处理代码,这可能会导致重新抛出异常,则必须抛出exception对象,而不是getMessage()方法返回的字符串

function _modulename_getData($field, $table) {
  try {
    if (empty($field)) {
      throw new Exception("The field is undefined."); 
    }
    // rest of code here...
  }
  catch (Exception $e) {
    if (some condition) {
        // do some handling
    } else {
        // the error is irrecoverable
        throw $e;
    }
  }
}

或者,如果你必须进行一些恢复,就像数据库事务中经常使用的那样:进行恢复,然后重新抛出:

  catch (Exception $e) {
      $db->rollback(); // rollback the transaction
      throw $e; // let the error to be handled the usual way
    }
  }

要重新进行

 throw $e;

而不是消息。

如果要处理错误,只需删除throw,或者如果只需要错误消息,则完全删除try-catch块。

这并不是告诉你只能在catch块中抛出对象,而是告诉你只能抛出对象,错误的位置在catch区块中——这是有区别的。

在catch块中,你试图抛出你刚刚抓到的东西——在这种情况下,这毫无意义——而你试图抛出的东西是一根绳子。

在现实世界中,你所做的事情是接球,然后试图把制造商的标志扔到其他地方。只能抛出整个对象,而不能抛出对象的属性。

您试图抛出string:

throw $e->getMessage();

您只能抛出实现'Throwable的对象,例如'Exception

附带说明:异常通常用于定义应用程序的异常状态,而不是用于验证后的错误消息。当用户向您提供无效数据

时,也不例外

Throw需要一个由'Exception实例化的对象。只有被抓到的$e才能发挥作用。

throw $e