How to efficiently use try…catch blocks in PHP

前端 未结 8 1420
自闭症患者
自闭症患者 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:18

    Important note

    The following discussion assumes that we are talking about code structured as in the example above: no matter which alternative is chosen, an exception will cause the method to logically stop doing whatever it was in the middle of.


    As long as you intend to do the same thing no matter which statement in the try block throws an exception, then it's certainly better to use a single try/catch. For example:

    function createCar()
    {
        try {
          install_engine();
          install_brakes();
        } catch (Exception $e) {
            die("I could not create a car");
        }
    }
    

    Multiple try/catch blocks are useful if you can and intend to handle the failure in a manner specific to what exactly caused it.

    function makeCocktail()
    {
        try {
            pour_ingredients();
            stir();
        } catch (Exception $e) {
            die("I could not make you a cocktail");
        }
    
        try {
            put_decorative_umbrella();
        } catch (Exception $e) {
            echo "We 're out of umbrellas, but the drink itself is fine"
        }
    }
    
    0 讨论(0)
  • 2020-12-02 06:21
    try
    {
        $tableAresults = $dbHandler->doSomethingWithTableA();
        if(!tableAresults)
        {
            throw new Exception('Problem with tableAresults');
        }
        $tableBresults = $dbHandler->doSomethingElseWithTableB();
        if(!tableBresults) 
        {
            throw new Exception('Problem with tableBresults');
        }
    } catch (Exception $e)
    {
        echo $e->getMessage();
    }
    
    0 讨论(0)
提交回复
热议问题