What are some best practices for handling errors in PDO connections in PHP?

When working with PDO connections in PHP, it is important to handle errors properly to ensure robust error management. One best practice is to set the PDO error mode to PDO::ERRMODE_EXCEPTION, which will throw exceptions when errors occur. This allows for more granular error handling and makes it easier to troubleshoot issues with database connections.

try {
    $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}