Handling Errors as Exceptions

Both mySQLi and PDO can handle process failed database calls either as errors or as exceptions. With PDO we turned on the exception processing in our first look at actually connecting to the database when we included the following in the call.


To have PDO treat failed database calls as errors we would simply omit that from the connect statement.

With mySQLi the preferred way of working is to treat failed calls as errors. Each can then be actioned directly after the call by testing for the error code or message returned (for example the duplicate key error we looked at in the insert example. If you want mySQL to treat failed calls as exceptions rather than errors then you can do so by including the following code before the block of code you want it to apply to.

$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

With exception processing turned on we can now wrap our database call inside of a try block and then use a catch block to catch and process the exception.

For example with mySQLi:

try {
// database call(s) go here
catch (mysqli_sql_exception $e) {

With PDO we would wrap it like this:

try {
// database call(s) go here
catch(PDOException $e) {
echo $e->getMessage();

In each case any one or more database calls can be included in the try block. The catch block in each case above shows how to simply display the message that is related to the exception that was thrown but we can of course include whatever code we like in the catch block.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow