捕获从匿名命名空间初始化抛出的异常

Catching an Exception Thrown From an Anonymous Namespace Initialization

本文关键字:异常 初始化 命名空间      更新时间:2023-10-16

当从在匿名命名空间中构造的类的构造函数抛出异常时,我得到一个未处理的异常错误。如何捕获异常?下面是一个简化的错误示例,试图在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被调用之前构造的,所以异常被抛出,甚至没有人能够捕捉到它。