3

Everything I've read says that they should be used when something that simply "shouldn't happen" does happen. But the thing is, there's a lot of things that could go wrong.

For example, if I'm accessing an object's property via the magic __get($property) method, it's possible that there would be no property called $property. So does this mean that I should wrap every $foo->bar in a try/catch?

And what about database queries? Do I really need to wrap every $stmt->execute() in a try/catch statement?

I feel like if I wrapped everything that could go wrong in a try/catch statement, I'd end up with several dozen try/catches per file!

1 Answers1

10

Everything I've read says that they should be used when something that simply "shouldn't happen" does happen. But the thing is, there's a lot of things that could go wrong.

That's about when you should throw, not when you should catch.

The point of a catch is to do something sensible when an error occurs. If you can't do anything sensible, don't catch the error. My SQL statement may fail, but I can't really do anything sensible if it does. The property I expected to be on an object may be missing, but I can't do anything sensible if it does.

On the other hand, if my connection to an external server times out, I could try again. If my client stops responding, I could disconnect it. If some unknown error occours while rendering my page, I can show an error message.

In general, the vast majority of cases are ones where there is no sensible recovery when something goes wrong. Things go wrong because of bugs in your code or configuration, and you should fix those bugs. There are a few cases where you can actually take meaningful action in the face of a bug, and those are the cases where you should catch the exceptions.

Winston Ewert
  • 25,052