What are the best practices for handling exceptions and error messages in PHP when working with databases like MySQL using PDO?

When working with databases like MySQL using PDO in PHP, it is important to handle exceptions and error messages properly to ensure robust error handling. One best practice is to use try-catch blocks to catch exceptions and handle them gracefully, providing informative error messages to the user or logging them for debugging purposes.

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