What are the best practices for handling error messages in PHP scripts, especially when dealing with database connections?

When handling error messages in PHP scripts, especially when dealing with database connections, it is important to use try-catch blocks to catch and handle exceptions gracefully. This helps in providing more meaningful error messages to the user and also prevents exposing sensitive information about the database connection.

try {
    $db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    // Other database operations
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}