Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions and return types

When throwing a new exception is it best to simply return true if no exception needs to be thrown. Alternatively is it best to return false instead of throwing an exception. Im using php.

like image 346
David Avatar asked Dec 13 '22 20:12

David


1 Answers

It all depends on what you're doing. Personally, I use them all the time so that I don't have to check a return value (A stupid, but illustrative example):

function ArrayToObject(array $array) {
    $obj = new StdClass();
    foreach ($array as $key => $value) {
        if (!is_string($key)) {
            throw new Exception('Expects only string keys in the array');
        }
        $obj->$key = $value;
    }
    return $obj;
}

That way, I can do:

$array = array('foo' => 'bar');
try {
    echo ArrayToObject($array)->foo; //Prints "bar"
} catch (Exception $e) {
    //Handle error here
}

It lets you not worry about error checking your results. You can handle the errors right in the catch block.

So no, don't alter what you're going to return based on the exceptions... Let the exceptions handle the errors and altered workflow for you...

A more real world example (in pseudo code):

try {
    open database connection;
    send query to database;
    operate on results;
} catch (DatabaseConnectionException $e) {
    handle failed connection here;
} catch (DatabaseQueryException $e) {
    handle failed query here;
} catch (Exception $e) {
    handle any other errors here;
}

Obviously, that's assuming your database functions/methods throw those exceptions...

like image 91
ircmaxell Avatar answered Dec 28 '22 10:12

ircmaxell