所以我正在为我正在编写的程序设置自定义异常类。我正在创建一个包罗万象的基类,我将主要将其用作通用异常。这个基类将被其他几个自定义异常继承。这是基类和附加异常类之一,将有 10 多个从父类继承的子类。
#include <exception>
#include <string>
#include <string.h>
class AgentException : public std::exception
{
protected:
char *msg;
public:
AgentException() : msg("AgentException"){};
AgentException(char *m) : msg(m){};
AgentException(char *m, std::string d)
{
strcat(m, d.c_str()); //aware this fails. its a segmentation fault
};
~AgentException() = default;
const char *what() const throw()
{
return (const char *)msg;
}
};
class ConnectionFailed : public AgentException
{
private:
std::string eType = "ConnectionFailed";
public:
ConnectionFailed() : AgentException("ConnectionFailed"){};
ConnectionFailed(std::string d) : AgentException("ConnectionFailed: ", d){};
~ConnectionFailed() = default;
};
我知道上面的代码 what() 当前不会返回任何内容,因为没有分配成员变量。我把它省略了,因为我从 strcat() 调用中得到了分段错误。
我为父类创建了多个构造函数,因为有时我希望传递默认值、单个值甚至两个参数。对于子类,它总是至少将类 ID 传递给父类,在某些情况下,我可能需要将字符串变量与类 id 一起传递。字符串变量 std::string 是必须的。这些是我被赋予使用的指令。
最初我在类中将所有消息变量设置为std::string,但我最终遇到了与what()函数相关的问题。我不知道如何将std::string转换为const char *。在做了一些研究之后,我发现在异常类中使用字符串是一个坏主意,因为什么会捕获其中可能发生的任何异常
所以我将所有内容都转换回const char *,但现在我似乎无法从what()获得回报。这些问题都源于我无法弄清楚不同类型的串联。
通过对 AgentException 类的更改,我可以得到一些可以正常工作的东西。
protected:
char msg[100];
public:
// AgentException() : msg("AgentException"){};
// AgentException(char *m) : msg(m){};
AgentException(const char *m, std::string d)
{
strcpy(msg, m);
strcat(msg, d.c_str());
};
我可以使这种改变整体发挥作用,但感觉这不是这样做的正确方法。有人可以让我了解他们将对这个设置做出的改变吗?
我目前正在通过抛出 AgentException 或 ConnectionFailed 异常并使用 Base AgentException 捕获来进行测试。我一直在旋转,看看是否有任何不同的反应。
try
{
throw ConnectionFailed("test");
}
catch (const AgentException &e)
{
std::cout << "----------------" << std::endl;
std::cerr << e.what() << '\n';
std::cout << "_________________" << std::endl;
}