Vladimir
Vladimir

Reputation: 1622

PHP: Can we return inside Try block

In some cases I don't care if Query fails or for example something === 1 , in both cases I want to return FALSE or die() etc..., so i do the following:

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

My question is, is it okay that I'm using throw new PDOException or should i use Exception instead of PDOException and then catch Exception too?

Upvotes: 0

Views: 1197

Answers (2)

woverton
woverton

Reputation: 481

This could be answered so many ways. Your way works but could be made a little clearer.

Here would be my take:

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

Upvotes: 2

Devon Bessemer
Devon Bessemer

Reputation: 35337

Yes, you can. Trying this code out should have told you that.

However, you don't need to. This would accomplish the same thing. Either way is fine, I'm just pointing this out.

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

Upvotes: 1

Related Questions