How can PHP developers effectively handle errors and exceptions when executing SQL queries?

When executing SQL queries in PHP, developers can effectively handle errors and exceptions by using try-catch blocks to catch any exceptions thrown during the query execution. This allows developers to gracefully handle errors and display meaningful error messages to users.

try {
    // Execute SQL query
    $result = $pdo->query("SELECT * FROM users");
    
    // Process query result
    foreach($result as $row) {
        // Handle query results
    }
} catch (PDOException $e) {
    // Handle any exceptions thrown during query execution
    echo "Error executing SQL query: " . $e->getMessage();
}