捕获从匿名命名空间初始化抛出的异常
Catching an Exception Thrown From an Anonymous Namespace Initialization
当从在匿名命名空间中构造的类的构造函数抛出异常时,我得到一个未处理的异常错误。如何捕获异常?下面是一个简化的错误示例,试图在Main.cpp中捕获它:
Main.cpp:
#include "Exception.hpp"
#include "Namespace.hpp"
int main()
try
{
return 0;
}
catch(Exception exception)
{
exception.show();
return 1;
}
Exception.hpp:
#pragma once
#include <iostream>
#include <string>
class Exception
{
std::string m_error;
public:
Exception(std::string error) : m_error(error){};
void show(){ std::cout<<m_error<<"n"; }
};
Namespace.hpp:
#pragma once
namespace Namespace
{
};
Namespace.cpp:
#include "Namespace.hpp"
#include "Class.hpp"
namespace
{
Class test_class{};
};
Class.hpp:
#pragma once
#include "Exception.hpp"
class Class
{
public:
Class(){ throw Exception{"Error Messagen"}; }
};
问题是你在匿名命名空间中声明的变量就像任何其他全局变量一样,它是在 main
被调用之前构造的,所以异常被抛出,甚至没有人能够捕捉到它。
相关文章:
- 对象初始化后在C++中显示 char 数组时的异常行为
- c++ 中的异常类何时初始化?
- 未找到匹配的运算符删除;如果初始化引发异常,内存将不会被释放
- 当使用lambda进行变量的复杂初始化时,如何处理从内部抛出的lambda外部异常
- 聚合初始化中出现异常
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- 初始化引发异常的对象
- 异常 尝试初始化动态数组时未处理
- 为什么初始化构造函数列表参数时会发生异常?
- 视觉C++ Int 似乎没有初始化并引发异常:读取访问冲突
- 如果初始化或销毁因未处理的异常而终止,则必须销毁完全构造的子对象
- 初始化不正确的价值不良样式后,正在抛出异常
- 如果从 c++ 中的构造函数引发异常,如何清理初始化的资源
- DLL 中的 C++ 静态局部变量初始化会导致_CrtIsValidHeapPointer异常
- 变量 C++ 的异常初始化
- std::互斥初始化异常
- 出现异常后重试本地静态变量初始化
- 类型初始化使用 OpenSsl.net 异常
- 每当我尝试初始化Employer对象时,我的程序都会给出一个未处理的异常错误
- TheoraVideoManager不会在0x7329E13D(msvcr110.dll)处初始化未处理的异常