正确尝试/捕获无序映射异常

Try/Catch unordered map exception properly

本文关键字:无序 映射 异常      更新时间:2023-10-16

我得到了这个:

// static enum of supported HttpRequest to match requestToString
static const enum HttpRequest {
    GET, 
    POST,
    PUT,
    DELETE,
    OPTIONS,
    HEAD,
    TRACE
};
// typedef for the HttpRequests Map
typedef boost::unordered_map<enum HttpRequest, const char*> HttpRequests;
// define the HttpRequest Map to get static list of supported requests
static const HttpRequests requestToString = map_list_of
    (GET,    "GET")
    (POST,   "POST")
    (PUT,    "PUT")
    (DELETE, "DELETE")
    (OPTIONS,"OPTIONS")
    (HEAD,   "HEAD")
    (TRACE,  "TRACE");

现在如果我打电话

requestToString.at(GET);

没关系,但是如果我调用不存在的键,例如

requestToString.at(THIS_IS_NO_KNOWN_KEY);

它给出了运行时异常,整个过程中止。

防止这种情况的最佳方法是什么? 是否有编译指示或其他东西,或者我应该"像Java一样"用try/catch块包围它或什么?

好心的亚历克斯

如果找不到

异常,请使用 at;如果不希望异常终止进程,请在某处处理异常;如果要在本地处理异常,请使用 find

auto found = requestToString.find(key);
if (found != requestToString.end()) {
    // Found it
    do_something_with(found->second);
} else {
    // Not there
    complain("Key was not found");
}
您可以使用

unordered_map::find来搜索可能在映射中也可能不在映射中的键。

find返回一个迭代器,如果未找到键,则为 == end (),如果找到键,则"指向"std::p air。

未编译的代码:

unordered_map < int, string > foo;
unordered_map::iterator iter = foo.find ( 3 );
if ( iter == foo.end ())
     ; // the key was not found in the map
else
     ; // iter->second holds the string from the map.

http://www.boost.org/doc/libs/1_38_0/doc/html/boost/unordered_map.html#id3723710-bb 的文档说:

抛出:类型 std::out_of_range 的异常对象(如果不存在此类元素)。

您可以

先使用unordered_map::findunordered_map::count来检查密钥是否存在。