【问题标题】:Try/Catch unordered map exception properly正确尝试/捕获无序地图异常
【发布时间】:2012-08-16 15:12:21
【问题描述】:

我有这个:

// 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);

它给出一个运行时异常并且整个过程中止..

防止这种情况的最佳方法是什么?是否有编译指示或什么,或者我应该用 try/catch 块或什么来“类 java”围绕它?

请亚历克斯

【问题讨论】:

  • static const enum??? staticconst 在类型定义中有什么含义吗?
  • 不要认为在这种情况下实际上需要 const 但无论如何:-)
  • 在这种情况下,enum 上的 staticconst 毫无意义。 C++ 不是 Java。在 C++ 中,enums 是具有限制范围的整数类型。

标签: c++ exception boost try-catch unordered-map


【解决方案1】:

如果你想在找不到异常的情况下使用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");
}

【讨论】:

  • 自动前缀到底是做什么的?如果我在我的解决方案中使用 find 我得到这个:错误 C2678:二进制“+”:没有找到运算符,它采用“std::string”类型的左操作数(或者没有可接受的转换)
  • @AlexTape:从用于初始化变量的表达式中推断出变量的类型。如果您不使用 C++11,那么不幸的是,您将不得不编写 boost::unordered_map&lt;enum HttpRequest, const char*&gt;::const_iterator(或为此编写更短的 typedef)。
【解决方案2】:

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

抛出:std::out_of_range 类型的异常对象,如果不存在这样的元素。

【讨论】:

  • hm 有没有办法在全球范围内声明这个捕获?我在不同的位置多次使用 .at 并且我不想用它来炸毁我的代码.. 有什么想法吗?
  • @AlexTape:除了终止程序之外,没有“全局”的方法来处理异常,因为没有通用的方法可以从任意错误中恢复。要么一开始就避免扔掉它们,要么将它们包含在你的设计中,弄清楚如何从它们中恢复,然后将 catch 块放在适当的位置。
  • @AlexTape 找到名为 main 的函数并使用如下内容:int main() { try { /* your code */ } catch(std::out_of_range) {return 1;} }
  • @anatolyg hehe 非常好的答案 :-) 简单的想法 :-)
  • @Alex Tape:如果你不想重复代码,把它放在一个函数中。
【解决方案3】:

您可以使用unordered_map::find 搜索可能在地图中也可能不在地图中的键。

find 返回一个迭代器,如果未找到密钥,则该迭代器是 == end (),如果找到密钥,则“指向”一个 std::pair。

未编译的代码:

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.

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • 是的,但是这两个函数都不返回引用的字符串,还是我错了?
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 2011-12-05
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多