From now on, I intend to use them much more in the PHP functions and class methods I write, rather than following the seemingly common practice of having these return null, false or -1.
Here’s an example of how Exceptions can neaten up code. This is a factory class that creates a new car object based on information retrieved from a database. I’m using this mysqli wrapper in this example.
abstract class car_factory
public function get($car_id)
$db = db::get();
if (!$db) throw new Exception(“Database connection failed.”);
$rows = $db->q(“select name, description where id = ? limit 1”, “i”, $car_id);
if (!$rows) throw new Exception(“Database query failed.”);
$row = $rows;
return new car($row[“id”], $row[“name”], $row[“description”]);
And below is how we’d call this get method.
catch (Exception $e)
echo “Dreadfully sorry, but an error occurred. Here are the details: “.$e->getMessage();
For those unfamilar with Try Catch blocks, this code will attempt to perform what is within the ‘try’ brackets. If an exception is thrown at any point during this, it will abort and run the code within the ‘catch’ brackets, creating a new PHPÂ Exception object, containing theÂ specificÂ details of the exception that was thrown.
This Exception objects contain a lot of methods that can be useful for error reporting and/or logging. Click the links in the list below to see the specific details on PHP.net.
- Exception::getMessageÂ â Gets the Exception message
- Exception::getPreviousÂ â Returns previous Exception
- Exception::getCodeÂ â Gets the Exception code
- Exception::getFileÂ â Gets the file in which the exception occurred
- Exception::getLineÂ â Gets the line in which the exception occurred
- Exception::getTraceÂ â Gets the stack trace
- Exception::getTraceAsStringÂ â Gets the stack trace as a string
- Exception::__toStringÂ â String representation of the exception
Using Exceptions, rather than returning null/false, or relying of PHP’s warnings, errors and notices, can generally result in easier management of errors.
For example, the above example could be easily modified to behave in a different manner dependentÂ on whether or not the website is in a live or development status, which could simply be determined by a global ‘$site_live’ boolean variable in one of the website’s main configuration files.