从匿名命名空间中构造的类的构造函数中抛出异常时,出现未处理的异常错误。我该如何捕捉异常?这是一个简单的错误示例,试图在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 Message\n"}; }
};
答案 0 :(得分:0)
问题是你在匿名命名空间中声明的变量就像任何其他全局变量一样,它是在调用 main
之前构造的,所以抛出异常没有任何人都能抓住它。