Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Does try/catch have a higher overhead than if/then?

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?

like image 820
bpeterson76 Avatar asked Dec 03 '22 04:12

bpeterson76


2 Answers

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.

like image 112
Fosco Avatar answered Dec 24 '22 23:12

Fosco


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.

like image 27
ircmaxell Avatar answered Dec 24 '22 22:12

ircmaxell