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

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

    In php by using Try Catch with inheritence, We can throw exception from another class.

    Example :- I am in the controller and validating user data by using Models.

    If any error triggers, I just have to throw exception from Model methods.

    The execution in try will break and catched in the Catch Block.

    So There is less overhead of returning bool vales and checking that.

    Apart from this Try Catch works great When using in chain ( Try - Catch inside another Try - Catch ).

提交回复
热议问题