3

This question already has an answer here:

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!

marked as duplicate by gnat, durron597, user22815, GlenH7, user40980 Nov 1 '15 at 1:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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. – Colonel Thirty Two Oct 31 '15 at 2:14
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.