How can PHP developers effectively handle exceptions like "Duplicate entry" in MySQL queries?

When handling exceptions like "Duplicate entry" in MySQL queries, PHP developers can use a try-catch block to catch the exception and handle it appropriately. They can check if the exception message contains the specific error message for duplicate entry and then take necessary actions, such as displaying an error message to the user or logging the error.

try {
    // Your MySQL query that may cause a duplicate entry exception
} catch (PDOException $e) {
    if ($e->errorInfo[1] == 1062) { // MySQL error code for duplicate entry
        // Handle the duplicate entry error here
        echo "Duplicate entry error: " . $e->getMessage();
    } else {
        // Handle other types of exceptions
        echo "An error occurred: " . $e->getMessage();
    }
}