Working in some legacy code, I've run across a ton of Try/Catch statements. Try/Catch isn't something that they taught in my Zend certification classes, and in 10 years I've not worked with another PHP developer who's used it. Does Try/Catch have extra overhead compared to doing if statements? What would make it more or less desirable than other options?
Of course it does. But the gains from making error handling that much easier are worth it.
I don't consider them to really be related to each other.
If statements are for determining branching logic.
Try/Catch is to handle errors that occur. Exceptions that would halt the program can be handled in the Catch block.
Try/catch is used for error handling. If statements are simple boolean testers. They don't do the same things at all. You should use if statements and test for each condition you know about, but use try/catch for exception handling.
The whole point of try/catch
is that it is non-local. You can exit multiple loops at a stroke, break out of nested function calls, escape from anywhere you get into. if
can't do that, and is not meant to. I do not know about the overhead, but I strongly and informedly suspect that it has much more than if. Ultimately, use the tool right for the job: they are not interchangeable.
Okay, they are, but they shouldn't be interchanged :)
UPDATE: Many other people say that try/catch
are for error handling. They are not. They are for exception handling. In many languages, for example, trying to get a next element from the iterator on its last element will raise an exception; this is a perfectly valid use of exceptions. You can use them whenever something unexpected happens, which has to be handled outside the current scope (assuming you are not providing a callback to handle it).
Well, if I understand correctly, a try/catch block adds a layer to the stack. So yes, there can be significant performance issues with it. However, the gains that it provides by letting you handle errors where you need to are significant as well. An if
statement has very little overhead. So to directly answer your question, yes try/catch has a significantly higher overhead than if/then (Throwing exceptions has a LOT more overhead, since it generates a backtrace for each throw).
With that said, they both have their purpose. Exceptions should be used for, well, exceptional conditions. You should use them to detect things that went wrong that are not within the normal realm of failure. For example, you wouldn't throw an exception if a user didn't enter a long enough password on the registration page. But you would throw an exception if you couldn't connect to the database to perform the registration. One is a logic error, and the other is a condition that needs to interrupt normal program flow.