PDO - Exception Handling

PDO has three error handling modes.

<?php
try {
  // Connect as appropriate as above.
  $db->query('hi'); // Invalid query!
} catch(PDOException $ex) {
  echo "An Error occured!"; // User friendly message.
  some_logging_function($ex->getMessage());
}

NOTE: You do not have to handle with try catch right away. You can catch it anytime that is appropriate. It may make more sense to catch it at a higher level like outside of the function that calls the PDO stuff:

<?php
function getData($db) {
  $stmt = $db->query("SELECT * FROM table");
  return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

…then much later…

try {
  getData($db);
} catch(PDOException $ex) {
  // Handle me.
}

or you may not want to handle the exception with try/catch at all, and have it work much like or die(); does. You can hide the dangerous error messages in production by turning display_errors off and just reading your error log.