What is the best practice for error handling in PHP when using PDO?

When using PDO in PHP, it is important to properly handle errors that may occur during database operations. One common practice is to set PDO to throw exceptions on errors, allowing for easier error handling. By catching these exceptions, you can gracefully handle errors and provide appropriate feedback to the user.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Perform database operations
    
} catch (PDOException $e) {
    echo "An error occurred: " . $e->getMessage();
}