How to efficiently use try…catch blocks in PHP

前端 未结 8 1706
自闭症患者
自闭症患者 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 05:55

    There is no any problem to write multiple lines of execution withing a single try catch block like below

    try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
    

    The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

    When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

    try{
        install_engine();
        install_break();
        }
        catch(Exception $e){
        show_exception($e->getMessage());
        }
    try{
    install_body();
    paint_body();
    install_interiour();
    }
    catch(Exception $e){
    throw new exception('Body Makeover faield')
    }
    

提交回复
热议问题