Catching PHP PDO exceptions

How to handle PHP PDO exceptions with the try and catch method to control the flow of any potential errors with PDO connections and queries.

The try and catch exceptions method is a more suited way to get a grasp on problems that coincidently if not handled will throw a fatal error for an uncaught exception bringing your code to a halt.

try {
//Do somehihng
} catch(Exception $e) {
//Error found
}

Now to handle PDO exceptions for a connection function:

function db_connect()
{
    $host = '127.0.0.1';
    $db_name = 'database_name';
    $db_user = 'root';
    $db_password = 'password';
    $db = "mysql:host=$host;dbname=$db_name;charset=utf8mb4";
    $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
    try {
        $db_con = new PDO($db, $db_user, $db_password, $options);
        return $db_con;
    } catch (PDOException $e) {
        echo "PDO Error: " . $e->getMessage();
    }
}

When calling this function to create a connection assuming the password/username is incorrect this will be outputted:

PDO Error: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

The PDO exception has been caught. If the details were correct then the connection object would be returned.

Now using this try and catch method for a PDO MySQL query:

try {
    $db = db_connect();
    $insert = $db->prepare("INSERT INTO `table` (`col`, `col2`) VALUES (?, ?)");
    $insert->execute([1, 'Gary']);
} catch (PDOException $e) {
    echo "Insert Error: " . $e->getMessage();
}

Once again the exception will be caught and handled properly when the insert query has an error and cannot complete.