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

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

    @Perchik:

    My general philosophy of error handling:

    You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it. You should use try {} catch {} in situations where you suspect something can/will go wrong and you don't want it to bring down the whole system, like network timeout/file system access problems, files doesn't exist, etc.

    Vexing exceptions

提交回复
热议问题