c++ - 处理异常时抛出异常

标签 c++ exception-handling try-catch

我正在阅读“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/

相关文章:

C++ 扩充 STL 数据结构

c++ - 前向声明和模板函数错误

jsf-2 - SRVE0260E : The server cannot use the error page specified for your application to handle the Original Exception printed below

javascript - Node.js 域模块的替代方案是什么?

r - R中的tryCatch block ,返回变量

c++ - ld在使用Waf时找不到库,但在不使用Waf时可以

c++ - 在 namespace 中定义并在多个翻译单元中使用的变量的链接

java - 获得有关每个抛出的异常(甚至已处理的异常)的通知

java - 捕获 GoogleJsonResponseException 但 e.getDetails() 返回 null

java - try catch 选择菜单