Using Exceptions and Try Catch Blocks in PHP

Although common place in most languages like C, C++, Java and so on, Exceptions and the use of Try Catch blocks are no where near as prevalent in the PHP code I’ve encountered.

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[0];

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *