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?
Working in some legacy code, I’ve run across a ton of Try/Catch statements. Try/Catch
Share
The whole point of
try/catchis 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.ifcan’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/catchare 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).