I am still getting the hang of Exception Handling in PHP; Here is the scenario where I am using the convention: There are times where I have a SQL query that I need to turn into an object, so I wrote this utility class/method.
Class A {
public static function getThatOneInstance(){
$sql = "SELECT id FROM table WHERE condition=met LIMIT 1";
$O = UtilsMysql::fetchIdIntoInstance($sql, __CLASS__, new Exception('Not Found!?'));
return $O;
}
}
Class UtilsMysql {
public static function fetchIdIntoInstance($sql, $Class, Exception $NotFoundE = NULL){
$O = NULL;
$r = mysql_query($sql);
if (!$r) throw new ExceptionMySQL($sql);
if (mysql_num_rows($r) > 0) {
list($id) = mysql_fetch_row($r);
$O = new $Class($id);
} elseif (!is_null($NotFoundE)) {
throw $NotFoundE;
}
return $O;
}
}
There are times, though, where if there is no result returned from the query it represents an Exceptional Circumstance, and so an Exception needs to be thrown. Because this is not uncommon, rather than always testing the returned value from the utility method, I have started passing in an Exception, that will be thrown if no results are found. This way, I have a contract with the function, if I pass in an exception, I can rely on the fact that it returns an Object (don't need to test it).
Is it acceptable to pass an Exception into a function that then may or may not throw it?