What is the advantage of using try {} catch {} versus if {} else {}

前端 未结 14 1422
忘掉有多难
忘掉有多难 2020-11-29 18:19

I am switching from plain mysql in php to PDO and I have noticed that the common way to test for errors is using a try / catch combination instead of if / else combinations.

14条回答
  •  無奈伤痛
    2020-11-29 18:33

    Throwing and catching an exception is an expensive operation compared with most any other primitive operation. If this is a piece of code that needs to perform well (eg, in a tight loop), you will want to look at your use case - if you expect the exceptions to be thrown relatively often, you will be better off with an if/else perforance-wise (unless the underlying code is just wrapping an exception for you, in which case there's no gain at all). If the exceptions are only thrown in rare circumstances, then you're better off with a try/catch to avoid the overhead of branching in a tight loop.

提交回复
热议问题