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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With