繁体   English   中英

在PHP Try Catch块中抛出异常

[英]Throwing exceptions in a PHP Try Catch block

我在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();
  }
}

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

提前致谢!

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;
    */
  }
}

要重新做

 throw $e;

不是消息。

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

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

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

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

throw $e->getMessage();

你试着扔一个string

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

抛出需要一个由\\Exception实例化的对象。 只有$e catched可以发挥作用。

throw $e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM