I'm reading the "C++ Programming Language 4th edition" book and have a question regarding a paragraph about exception handling:
我正在阅读《c++编程语言第4版》,有一个关于异常处理的问题:
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.
如果异常处理实现捕获了您的操作,那么它将终止您的程序。
Could someone give me an example of the first situtation? Only something like this comes to my mind but it's a valid code according to g++:
谁能给我举一个第一个情况的例子?只有这样的事情出现在我的脑海中,但它是根据g++的有效代码:
try
{
throw 1;
}
catch(...)
{
try
{
throw 2;
}
catch(...)
{
cout << "OK";
}
}
1 个解决方案
#1
12
That's a bit misleading; it's fine to throw from an exception handler (which is what I'd understand by "while handling an exception"), as long as there's another handler to catch it.
这有点误导;只要有另一个处理程序来捕获异常,从异常处理程序中抛出(这是我理解的“处理异常时”)是可以的。
The problem is if you throw an exception from the destructor of an object that's being destroyed during stack unwinding. In that case, there are two unhandled exceptions, and the usual exception mechanism can only deal with one; so the response is to call terminate
.
问题是,如果从堆栈展开期间正在销毁的对象的析构函数中抛出异常。在这种情况下,有两个未处理的异常,通常的异常机制只能处理一个;因此响应是调用terminate。
Example:
例子:
struct dodgy {~dodgy() {throw "Don't do this!";}};
try {
dodgy d;
throw 1;
} catch (...) {
// Never reached: destroying `d` killed the program.
}
#1
12
That's a bit misleading; it's fine to throw from an exception handler (which is what I'd understand by "while handling an exception"), as long as there's another handler to catch it.
这有点误导;只要有另一个处理程序来捕获异常,从异常处理程序中抛出(这是我理解的“处理异常时”)是可以的。
The problem is if you throw an exception from the destructor of an object that's being destroyed during stack unwinding. In that case, there are two unhandled exceptions, and the usual exception mechanism can only deal with one; so the response is to call terminate
.
问题是,如果从堆栈展开期间正在销毁的对象的析构函数中抛出异常。在这种情况下,有两个未处理的异常,通常的异常机制只能处理一个;因此响应是调用terminate。
Example:
例子:
struct dodgy {~dodgy() {throw "Don't do this!";}};
try {
dodgy d;
throw 1;
} catch (...) {
// Never reached: destroying `d` killed the program.
}