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
  • 2
    What are you going to do in the catch blocks? If you're going to do something useful, like display a friendly dialog saying that a file wasn't found, then it's worthwhile. If you're just going to mimic the same "can't access nonexistent property" error message that would happen without the try/catch, there's literally no point. Oct 31, 2015 at 2:14

1 Answer 1

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.

2
  • "My SQL statement may fail, but I can't really do anything sensible if it does." I disagree with this, it would be far more useful to throw an error and log the issue with the data that was passed so it can be addressed and prevented from happening again.
    – Epoch
    Mar 4 at 11:44
  • @MDev20, of course. But that's not what I'm talking about. You can't actually recover from the error in any reasonable case. But you can log the error so you can resolve the underlying cause. Mar 4 at 19:21