What are best practices for error handling when executing PDO statements in PHP?

When executing PDO statements in PHP, it is important to handle errors properly to ensure the robustness of your application. One common practice is to set the PDO error mode to exception mode, which will throw exceptions when errors occur during query execution. This allows you to catch and handle these exceptions in a structured way, providing more detailed information about the error.

try {
    $dbh = new PDO($dsn, $username, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Execute your PDO statements here

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}