Hash Maps using std::unordered_map

Error Handling in std::unordered_map

How can I handle errors and exceptions when using std::unordered_map?

Abstract art representing computer programming

When working with std::unordered_map, there are a few common errors and exceptions you may encounter. Here are some ways to handle them:

Key Not Found

When trying to access a key that doesn't exist in the map using the [] operator or the at() function, you can handle it in two ways:

  • Use the [] operator and check if the key exists before accessing the value. If the key doesn't exist, it will be inserted with a default-constructed value.
  • Use the at() function, which throws a std::out_of_range exception if the key is not found. Catch the exception to handle the error.
#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  std::unordered_map<std::string, int> map{
    {"A", 1}, {"B", 2}};

  // Using [] operator
  if (map.count("C") == 0) {
    std::cout << "Key 'C' not found\n";
  } else {
    int value = map["C"];
  }

  // Using at() function
  try {
    int value = map.at("D");
  } catch (const std::out_of_range& e) {
    std::cout << "Key 'D' not found: "
      << e.what() << '\n';
  }
}
Key 'C' not found
Key 'D' not found: invalid unordered_map<K, T> key

Insertion Failure

When inserting a new element using insert() or emplace(), the operation may fail if an element with the same key already exists. You can check the return value of these functions to handle the failure.

#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  std::unordered_map<std::string, int> map{
    {"A", 1}, {"B", 2}};

  // Insertion using insert()
  auto result1 = map.insert({"A", 3});
  if (!result1.second) {
    std::cout << "Insertion failed: "
      "key 'A' already exists\n";
  }

  // Insertion using emplace()
  auto result2 = map.emplace("C", 3);
  if (!result2.second) {
    std::cout << "Insertion failed: "
      "key 'C' already exists\n";
  }
}
Insertion failed: key 'A' already exists

Memory Allocation Failure

In rare cases, memory allocation for new elements may fail due to insufficient memory. This will throw a std::bad_alloc exception. Catch the exception to handle the error gracefully.

#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  try {
    std::unordered_map<std::string, int> map;
    // Simulate memory allocation failure
    throw std::bad_alloc();
  } catch (const std::bad_alloc& e) {
    std::cout << "Memory allocation failed: "
      << e.what() << '\n';
  }
}
Memory allocation failed: bad allocation

By anticipating and handling these common errors and exceptions, you can write more robust and reliable code when using std::unordered_map. It's important to consider the specific requirements and error handling strategies of your application to ensure appropriate error handling and recovery.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved