PDO try-catch usage in functions

Your implementation is just fine, and it’ll work perfectly well for most purposes.

It’s not necessary to put every query inside a try/catch block, and in fact in most cases you actually don’t want to. The reason for this is that if a query generates an exception, it’s the result of a fatal problem like a syntax error or a database issue, and those are not issues that you should be accounting for with every query that you do.

For example:

try {
    $rs = $db->prepare('SELECT * FROM foo');
    $rs->execute();
    $foo = $rs->fetchAll();
} catch (Exception $e) {
    die("Oh noes! There's an error in the query!");
}

The query here will either work properly or not work at all. The circumstances where it wouldn’t work at all should not ever occur with any regularity on a production system, so they’re not conditions that you should check for here. Doing so is actually counterproductive, because your users get an error that will never change, and you don’t get an exception message that would alert you to the problem.

Instead, just write this:

$rs = $db->prepare('SELECT * FROM foo');
$rs->execute();
$foo = $rs->fetchAll();

In general, the only time that you’ll want to catch and handle a query exception is when you want to do something else if the query fails. For example:

// We're handling a file upload here.
try {
    $rs = $db->prepare('INSERT INTO files (fileID, filename) VALUES (?, ?)');
    $rs->execute(array(1234, '/var/tmp/file1234.txt'));
} catch (Exception $e) {
    unlink('/var/tmp/file1234.txt');
    throw $e;
}

You’ll want to write a simple exception handler that logs or notifies you of database errors that occur in your production environment and displays a friendly error message to your users instead of the exception trace. See http://www.php.net/set-exception-handler for information on how to do that.

Leave a Comment