How can one implement error handling in PHP when working with database queries, especially with deprecated functions like mysql_?

When working with database queries in PHP, especially with deprecated functions like mysql_, it is essential to implement error handling to ensure the stability and security of your application. One way to handle errors is by using try-catch blocks to catch exceptions thrown by database operations and display appropriate error messages to the user.

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM users";
    $result = $conn->query($sql);

    if ($result === false) {
        throw new Exception("Error: " . $conn->error);
    }

    // Process the query result here

    $conn->close();
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}