views:

43

answers:

3

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.

A: 

If a function does not have anything to return, it should return nothing.

Sjoerd
+3  A: 

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...

ircmaxell
A: 

It depends on the purpose of your function and the reason for returning. Use exceptions to return from the function during error/unexpected conditions. Use return values for standard operations.

Likewise, don't use return values to flag unexpected situations. If your function will not return anything meaningful for a null pointer reference, divide by zero, no data connection, you should throw the exception. One, it let's you isolate your error handling code with the catch block. Two, it lets you provide more information why it failed rather than just 'false'. Very annoying when something fails and all the info you get is just 'error'.

In addition, you don't want to throw exceptions as an alternative to flow control. You could get creative and write a compare function that did nothing if it was equal, threw an GreaterThanException or LessThanException if it was not equal. But, now you've lost the advantage of separating out the error handling code (since standard processing code is now contained in the catch blocks along with error code). Also, while I'm not sure of the performance of exception handling in many environments like php, it's probably more expensive with creating the exception object and doing the type comparison for catch blocks rather than just returning.

doobop