views:

106

answers:

4

Hi,

I have a PHP script that runs database queries. Now, if a query fails, should I trigger an error or throw an exception? I noticed that if I do the latter, the script execution will stop after facing the exception.

My code is as follows:

if (!$this->connection[0]->query($this->query))
    throw new Exception($this->connection[0]->error);

What are the pros and cons of using exceptions for this kind of cases (failed queries)?

+2  A: 

depends on your general error handling strategy and the queries passed to this function. Throwing Exceptions itself is a very good idea, IMHO, if they are caught somewhere and processed.

soulmerge
+1  A: 

I think it depends on how bad the situation is if the query fails. If it is critical that the query execute properly, then definitely go with the exception.

Whichever you decide, make sure that you handle the error/exception gracefully. (try..catch, etc).

You should also take a look at this stackoverflow question.

Abinadi
A: 

If this is for an external website, I tend to handle errors in detail in development stage. Once the site is ready to go live, I try not to give too much detail to the end user about errors, especially database details for security reasons.

This isn't some set in stone answer, but keep security in mind when reporting and handling errors on external sites. Just a note as this might not be an external website.

Troggy
+2  A: 

What are the pros and cons of using exceptions for this kind of cases (failed queries)?

Simply:

  • Pros: your application can handle the failed query gracefully, log it if need be, and move on.
  • Cons: performance.

That said, I think you may be focusing on the wrong question. You should be handling exceptions whenever they might happen, but they should happen very, very rarely. If your query has a reasonable chance of failing, then the query itself should be your focus rather than any error-handling mechanism.

By this I mean improving the validation of any input to your query that could cause it to choke, and not the speed of the query as a means to offset any performance hit due to error handling. In other words, find out what would make your query fail and ensure that such a state is not achieved.

Consider this analogy: if you're heading out onto the lake in a potentially leaky boat (your query), you shouldn't be worrying so much about wearing a wetsuit (error handling) as you should be about making sure the boat is watertight.

Cal Jacobson