c++ - 有什么方法可以捕获在构造静态/全局时抛出的异常?

标签 c++ exception

考虑以下可怕的事情:

#include <iostream>

struct thing
{
    thing()
    { 
        std::cout << "thing ctor\n";
        throw 5; 
    }
};

void SomeTerminateHandler()
{
    std::cout << "Uncaught exception!?\n";
}

int IHopeThisGetsCalledFirst()
{
    std::cout << "IHopeThisGetsCalledFirst()\n";
    std::set_terminate(SomeTerminateHandler);
    return 2;
}

const int x = IHopeThisGetsCalledFirst();
const thing y;

int main()
{
}

输出:

IHopeThisGetsCalledFirst()
thing ctor
Uncaught exception!?

这依赖于静态初始化顺序 ( which I can mess with, for MSVS anyway ),所以即使以下问题有可接受的答案,它也不是理想的。

  • 我可以在 SomeTerminateHandler 中做什么来“捕获”异常,以便显示错误对话框或记录错误的详细信息?
  • abort是在上述程序的SomeTerminateHandler之后调用的。为什么? This说“终止处理程序默认调用 cstdlib 的中止函数。” - 但我没有使用默认的终止处理程序,我的也没有调用 abort

我能做些什么来处理静态初始化时的异常。如果不是,为什么不呢?为什么语言中没有允许这样做的内容?

最佳答案

What can I do in SomeTerminateHandler to 'catch' the exception so I can display an error dialog box or log out the details of the error?

无 - 只有异常处理程序可以访问抛出的异常。

abort is called after SomeTerminateHandler in the above program. Why?

您的终止处理程序不得返回;标准(C++11、18.8.3.1)要求它“应终止程序的执行而不返回给调用者”——您链接到的页面也说了同样的话。如果您违反了该要求,那么任何事情都可能发生。

Is there anything I can do to handle exceptions in static initialization time?

您可以在构造函数中捕获异常;或者您可以避免使用复杂的静态对象。

If not, why not? Why isn't there something in the language to allow this?

我无法回答为什么,但 C++ 根本不能很好地处理复杂的静态对象。即使您的编译器确实有非标准扩展来指定初始化顺序,我还是建议尽可能避免使用它们。

关于c++ - 有什么方法可以捕获在构造静态/全局时抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9503533/

相关文章:

java - Java 和 Hibernate 中的 ArrayIndexOutOfBoundsException

python - 遇到第一个异常时,如何使scrapy crawl 中断并退出?

c++ - mem_fun_ref 麻烦

c++ - WAP八进制转二进制

c++ - 如何在C++中比较 vector 的元素?

c++ - 潜在 throw 函数是否信号安全?

java - 如何重用抛出异常的过程?

python - 抑制 Python 中捕获的异常的回溯(堆栈跟踪)

python - Boost Python - 全局和本地字典

c++ - 在 MFC 中更改按钮的光标