Posted on 2013-05-17 10:56
魏尚堂 阅读(138)
评论(0) 编辑 收藏 引用
Depending on the precise conditions under which such pairs of simultaneously active exceptions arise, program execution either terminates or yields undefined behavior. In this example, it yields undefined behavior.
C++ does not like destructors that emit exceptions!
#include <iostream>
#include <vector>
struct Exception
{
Exception(){std::cout << "Exception Constructor" << std::endl;}
~Exception(){std::cout << "Exception Destructor" << std::endl;}
};
class Widget {
public:
~Widget() {std::cout << "Widget Destructor" << std::endl; throw Exception();
} //this might emit an exception
void print(){std::cout << "print" << std::endl;}
};
void doSomething();
int main()
{
doSomething();
}
void doSomething()
{
std::vector<Widget> v;
v.push_back(Widget());
v.push_back(Widget());
v.push_back(Widget());
v.push_back(Widget());
std::vector<Widget>::iterator it = v.begin();
while(it != v.end())
{
std::cout << "end" << std::endl;
(*it).print();
it++;
}
}
complie with g++
[shangtang@BTSOM-1 study]$ ./a.out
Widget Destructor
Exception Constructor
terminate called after throwing an instance of 'Exception'
Aborted (core dumped)
There are two primary ways to avoid the trouble.
1, Terminate the program if catch a exception, typically by calling std::abort (cstdlib)
2, Swallow the exception if catch a exception, print a log