我正在尝试在 std::map
中使用 operator[]
来使用键读取元素。
但是当我尝试访问无效 key 时,它会抛出一个异常,我无法使用 try
-catch
block 捕获该异常。
这是我使用的代码:
class MapElement
{
public:
int a;
char c;
};
int main()
{
MapElement m1,m2,m3;
m1.a =10;m1.c = 'a';
m2.a =20;m2.c ='b';
m3.a =30;m3.c ='c';
map <char ,MapElement*> Mymap;
map<char,MapElement*>::iterator iter = Mymap.begin();
Mymap.insert(iter , std::pair<int, MapElement*>('1',&m1));
Mymap.insert(iter , std::pair<int, MapElement*>('1',&m2));
cout<<Mymap['1']->a;
try
{
cout<<Mymap['2']->a;
}
catch(exception e)
{
cout<<e.what();
}
catch(...)
{
cout<< "unknown error";
}
}
我该如何处理这个异常?
最佳答案
问题是由 std::map::operator[]
引起的为不存在的 key 创建新条目:
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
在这种情况下,该值是一个指针,它不会指向有效的 MapElement
。
这不是运行时故障,而是程序员错误,并导致未定义的行为。即使可以捕获此类错误,也不应以允许程序继续的方式捕获它,因为程序可能会表现出其他意外行为。
使用std::map::at()
如果你的编译器支持 c++11:
try
{
std::cout<< Mymap.at('2') << std::endl;
}
catch (std::out_of_range& const e)
{
std::cerr << e.what() << std::endl;
}
(参见 http://ideone.com/FR4svY 示例)。
否则,如果你的编译器不支持 c++11 使用
std::map::find()
,如果映射不包含请求的键,它不会抛出异常但返回 std::map::end()
:
template <typename K, typename V>
V& map_at(std::map<K, V>& a_map, K const& a_key)
{
typename std::map<K, V>::iterator i = a_map.find(a_key);
if (a_map.end() == i)
{
throw std::out_of_range("map_at()");
}
return i->second;
}
try
{
std::cout<< map_at(Mymap, '2') << std::endl;
}
catch (std::out_of_range& const e)
{
std::cerr << e.what() << std::endl;
}
(参见 http://ideone.com/lIkTD3 示例)。
关于c++ - 使用 std::map 时无法捕获未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20191905/