c++ - 捕获异常后崩溃

标签 c++ exception

为什么捕获 std::bad_exception 后会崩溃? (我用的是VC7)

#include "stdafx.h"
#include <exception>

int validateInt (int x) throw (int,std::bad_exception) {
    if ( 0 == x ) {
        throw std::bad_exception("x");
    }
    return x;
}

class C {  
    int i;    
public:  
    C(int);  
};  

C::C(int ii)  
try : i( validateInt(ii) ) {  
    std::cout << "I'm in constructor function body\n";
} catch (std::exception& e) {  
    std::cout << "I caught an exception...\n";
}

int _tmain(int argc, _TCHAR* argv[]) {
    C a(0);
    return 0;
}

最佳答案

因为你无法阻止异常离开构造函数初始化列表。捕获它后,它会自动重新抛出。 (然后它崩溃了,因为你有一个未处理的异常。)

这是一件好事:如果您的成员不能正确初始化,您的类就不能正确存在。

关于c++ - 捕获异常后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6730297/

相关文章:

ios - Thread1 信号 SIGABRT 表示 NSInvalid Argument Exception

java - 写入客户端 channel 时出现异常 java.nio.channels.ClosedChannelException

c++ - 如何将标准库与 C++ 模块一起使用? (例如 : `import std.io` )

c++ - 我可以调用调整大小事件而不用在 Qt 中手动调整大小吗?

c++ - 在 while 循环中打印零

c++ - 私有(private)或 protected 继承中的虚函数

c# - 将 C# API 编写为 C++ 代码的包装器?

php - 只捕获 SimpleXML 异常?

android - ANR keyDispatchingTimedOut 但堆栈跟踪中没有自己的类

exception - Crashlytics 是否管理离线崩溃。