Ale*_*ape 2 c++ boost unordered-map exception try-catch
我有这个:
\n\n// static enum of supported HttpRequest to match requestToString\nstatic const enum HttpRequest {\n GET, \n POST,\n PUT,\n DELETE,\n OPTIONS,\n HEAD,\n TRACE\n};\n\n// typedef for the HttpRequests Map\ntypedef boost::unordered_map<enum HttpRequest, const char*> HttpRequests;\n\n// define the HttpRequest Map to get static list of supported requests\nstatic const HttpRequests requestToString = map_list_of\n (GET, "GET")\n (POST, "POST")\n (PUT, "PUT")\n (DELETE, "DELETE")\n (OPTIONS,"OPTIONS")\n (HEAD, "HEAD")\n (TRACE, "TRACE");\nRun Code Online (Sandbox Code Playgroud)\n\n现在如果我打电话
\n\nrequestToString.at(GET);\nRun Code Online (Sandbox Code Playgroud)\n\nit\xc2\xb4s 好的,但是如果我调用一个不存在的密钥,例如
\n\nrequestToString.at(THIS_IS_NO_KNOWN_KEY);\nRun Code Online (Sandbox Code Playgroud)\n\n它给出了运行时异常并且整个过程中止..
\n\n防止这种情况的最好方法是什么?是否有一个编译指示或什么,或者我应该“像java一样”用try/catch块或什么包围它?
\n\n亲切的亚历克斯
\n如果您希望在未找到异常时使用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");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3738 次 |
| 最近记录: |