PHP Error handling: die() Vs trigger_error() Vs throw Exception

The first one should never be used in production code, since it’s transporting information irrelevant to end-users (a user can’t do anything about “Cannot connect to database”).

You throw Exceptions if you know that at a certain critical code point, your application can fail and you want your code to recover across multiple call-levels.

trigger_error() lets you fine-grain error reporting (by using different levels of error messages) and you can hide those errors from end-users (using set_error_handler()) but still have them be displayed to you during testing.

Also trigger_error() can produce non-fatal messages important during development that can be suppressed in production code using a custom error handler. You can produce fatal errors, too (E_USER_ERROR) but those aren’t recoverable. If you trigger one of those, program execution stops at that point. This is why, for fatal errors, Exceptions should be used. This way, you’ll have more control over your program’s flow:

// Example (pseudo-code for db queries):

$db->query('START TRANSACTION');

try {
    while ($row = gather_data()) {
       $db->query('INSERT INTO `table` (`foo`,`bar`) VALUES(?,?)', ...);
    }
    $db->query('COMMIT');
} catch(Exception $e) {
    $db->query('ROLLBACK');
}

Here, if gather_data() just plain croaked (using E_USER_ERROR or die()) there’s a chance, previous INSERT statements would have made it into your database, even if not desired and you’d have no control over what’s to happen next.

Leave a Comment