How to efficiently use try…catch blocks in PHP

前端 未结 8 1613
自闭症患者
自闭症患者 2020-12-02 05:31

I have been using try..catch blocks in my PHP code, but I\'m not sure if I\'ve been using them correctly.

For example, some of my code looks like:

 t         


        
8条回答
  •  攒了一身酷
    2020-12-02 06:05

    When an exception is thrown, execution is immediately halted and continues at the catch{} block. This means that, if you place the database calls in the same try{} block and $tableAresults = $dbHandler->doSomethingWithTableA(); throws an exception, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will not occur. With your second option, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will still occur since it is after the catch{} block, when execution has resumed.

    There is no ideal option for every situation; if you want the second operation to continue regardless, then you must use two blocks. If it is acceptable (or desirable) to have the second operation not occur, then you should use only one.

提交回复
热议问题