How can you handle database query errors in PHP without using die() or exit()?

When handling database query errors in PHP, it is important to avoid using die() or exit() as they abruptly terminate the script and do not provide a graceful way to handle errors. Instead, you can use try-catch blocks to catch exceptions thrown by the database queries and handle them appropriately within the catch block. This allows you to log the error, display a user-friendly message, or perform any other necessary actions without abruptly ending the script execution.

try {
    // Perform database query
    $result = $pdo->query("SELECT * FROM table");
    
    // Process query result
    // ...
    
} catch (PDOException $e) {
    // Handle database query error
    // Log the error, display a message, etc.
    echo "An error occurred: " . $e->getMessage();
}