【发布时间】:2021-10-27 05:50:35
【问题描述】:
我正在尝试重写 what 函数以打印我自己的自定义错误消息。
所有消息都有相同的开头,因此我认为如果我可以执行以下操作会是最好的:
class Exception : public std::exception
{
public:
virtual const char* what() const throw() noexcept
{
return ("A game related error has occurred: " + "class name");
//note : "class name" above is the error message I want to print
//depending on the situation, which can vary a lot(we have 8 different messages)
}
};
//examples of "class name" /otherwise known by us as error messages:
class IllegalArgument : public Exception {};
class IllegalCell : public Exception {};
我的问题如下:
我不知道如何根据收到的错误打印不同的消息 没有在每个错误类中创建特殊的 what 函数 - 这意味着我必须向 IllegalArgument、IllegalCell 和所有其他错误类添加一个 what 函数,这在我看来很糟糕,因为它有太多的函数无法支持并不断更新超时。无论如何我可以避免这种情况,并且能够在主类中打印不同的消息 - 异常?
【问题讨论】:
-
确保签名对于您使用的 C++ 版本是正确的:en.cppreference.com/w/cpp/error/exception/what(您现在有 throw() 和 noxcept,只需要一个)
-
只需将类名传递给您的
Exception构造函数并在what()中使用它。如果你对可能奇怪的类名感到满意,你可以使用typeid(*this).name()来检索类名。 -
我们使用的签名确实是正确的,我用的是c++11。
-
霍尔特,你能再解释一下吗?
-
@Saleh 看看我的回答。
标签: c++ c++11 exception overriding virtual-functions