Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct way of using a throw try catch error handling

I have come accross to this function below and I am wondering wether this is the right way of using the error handling of try/catch.

public function execute()
{
    $lbReturn = false;
    $lsQuery = $this->msLastQuery;
    try
    {
        $lrResource = mysql_query($lsQuery);

        if(!$lrResource)
        {
            throw new MysqlException("Unable to execute query: ".$lsQuery);
        }
        else
        {
            $this->mrQueryResource = $lrResource;
            $lbReturn = true;
        }

    }
    catch(MysqlException $errorMsg)
    {
        ErrorHandler::handleException($errorMsg);
    }
    return $lbReturn;
}
like image 916
sanders Avatar asked Dec 22 '22 11:12

sanders


2 Answers

Codewise it is correct/works, However the power of try-catch is that when an Exception is thrown from deep down in one of the functions you're calling.
Because of the "stop execution mid-function and jump all the way back to the catch block".

In this case there are no deep-down exceptions therefore I would write it like this:
(Assuming there is a function "handleErrorMessage" in the ErrorHandler.)

public function execute() {
    $lsQuery = $this->msLastQuery;
    $lrResource = mysql_query($lsQuery);

    if(!$lrResource) {
         ErrorHandler::handleErrorMessage("Unable to execute query: ".$lsQuery);
         return false;
    }
    $this->mrQueryResource = $lrResource;
    return true;
}

Which I find more readable.

like image 122
Bob Fanger Avatar answered Feb 04 '23 21:02

Bob Fanger


No. Throwing an exception in this case is simply a GOTO, but with a (slightly) prettier face.

like image 34
PaulJWilliams Avatar answered Feb 04 '23 20:02

PaulJWilliams