Would I want to throw an exception or an error in this PHP script?

荒凉一梦 提交于 2019-12-13 04:56:42

问题


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)?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/1069617/would-i-want-to-throw-an-exception-or-an-error-in-this-php-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!