在PHP Try Catch块中抛出异常

kas*_*ord 69 php exception-handling try-catch drupal-6

我在Drupal 6 .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();
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行代码时,它告诉我对象只能在Catch块中抛出.

提前致谢!

Ali*_*guy 100

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;
    */
  }
}
Run Code Online (Sandbox Code Playgroud)


Che*_*rot 65

要重新做

 throw $e;
Run Code Online (Sandbox Code Playgroud)

不是消息.

  • 这会保留堆栈信息,还是会覆盖它? (5认同)
  • 保留,以覆盖抛出新的e (3认同)

Dav*_*dom 16

只需throw从catch块中删除- 将其更改为echo或以其他方式处理错误.

它没有告诉你只能在catch块中抛出对象,它告诉你只能抛出对象,并且错误的位置在catch块中 - 存在差异.

在catch块中,你试图抛出你刚抓到的东西 - 在这种情况下无论如何都没有意义 - 而你试图抛出的东西是一个字符串.

你正在做的事情的真实世界类比是接球,然后试图在其他地方抛出制造商的标志.您只能抛出整个对象,而不是对象的属性.


Kin*_*nch 7

throw $e->getMessage();
Run Code Online (Sandbox Code Playgroud)

您尝试扔一个 string

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

  • @lazycommit“无效数据”有点笼统。如果您指的是“用户提供的无效值”,那么从应用程序的角度来看它们并不是无效的,因为应用程序_必须_期望这样做,因此必须对它们进行适当的处​​理(->验证)。如果稍后在处理过程中(从后端或由于未正确验证)传递了无效数据,则“是”:异常。总结一下:不要将`Exception`用于控制流(此处:验证):) (4认同)
  • 不。无效数据是例外的原因 (2认同)