PHP:我们可以在Try块内返回吗?


PHP: Can we return inside Try block

在某些情况下,我不在乎查询是否失败,或者例如某事=== 1,在这两种情况下,我都想要return FALSE or die() etc...,所以我做以下操作:

function test($db){
  try
  {
     $stmt = $db->query("SELECT * FROM table WHERE id=1")->fetch(PDO::FETCH_ASSOC);
     // If Query fails, PDO itself will throw exception,
     // but i also check the value here and throw exception if it's not !== 1
     if ($stmt['column'] === 1)
     {
        throw new PDOException('Wrong Column Info');
     }
     else
     {
        return TRUE;
     }
  }
  catch(PDOException $e)
  {
     return FALSE;
  }
}

我的问题是,它是可以的,我使用throw new PDOException或我应该使用Exception而不是PDOException,然后捕获异常?

这个问题有很多种解释。你的方法是有效的,但可以更清楚一些。

我的看法是:

function test($db){
  try
  {
     $stmt = $db->query("SELECT * FROM table WHERE id=1")->fetch(PDO::FETCH_ASSOC);
     // If Query fails, PDO itself will throw exception,
     // but i also check the value here and throw exception if it's not !== 1
     if ($stmt['column'] === 1)
     {
        throw new PDOException('Wrong Column Info');
     }
     return true;
  }
  catch(PDOException $e)
  {
     error_log("Query failed!");
  }
  return false;
}

可以。尝试这段代码应该告诉你:

然而,你不需要。这将完成同样的事情。两种方式都可以,我只是指出这一点。

function test($db){
  try
  {
     $stmt = $db->query("SELECT * FROM table WHERE id=1")->fetch(PDO::FETCH_ASSOC);
     // If Query fails, PDO itself will throw exception,
     // but i also check the value here and throw exception if it's not !== 1
     if ($stmt['column'] === 1)
     {
        throw new PDOException('Wrong Column Info');
     }
  }
  catch(PDOException $e)
  {
     return FALSE;
  }
  return TRUE;
}