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

前端 未结 14 1483
忘掉有多难
忘掉有多难 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:45

    Everybody else had good answers - but I figured I would throw my own in:

    1. Try/Catch is an actual exception handling mechanism - so if you change your exceptions, it will automatically work on all try/catch statements.
    2. Try/Catch gives the opportunity to run code even in the case of a major exception that might kill the if/else and in addition, the try statement can be rolled back (if you're savvy).

提交回复
热议问题