我正在阅读“C++ Programming Language 4th edition”一书,对有关异常处理的段落有疑问:
There are cases where exception handling must be abandoned for less subtle error-handling techniques. The guiding principles are:
- Don't throw an exception while handling an exception.
- Don't throw an exception that can't be caught.
If the exception-handling implementation catches you doing either, it will terminate your program.
有人可以给我一个第一种情况的例子吗?我只想到了这样的事情,但根据 g++,它是一个有效的代码:
try
{
throw 1;
}
catch(...)
{
try
{
throw 2;
}
catch(...)
{
cout << "OK";
}
}
最佳答案
这有点误导;可以从异常处理程序中抛出(这是我对“处理异常时”的理解),只要有另一个处理程序可以捕获它。
问题是,如果您从在堆栈展开期间被销毁的对象的析构函数中抛出异常。那样的话,有两个未处理的异常,通常的异常机制只能处理一个;所以响应是调用 terminate
。
例子:
struct dodgy {~dodgy() {throw "Don't do this!";}};
try {
dodgy d;
throw 1;
} catch (...) {
// Never reached: destroying `d` killed the program.
}
关于c++ - 处理异常时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17838830/