c++ - 在 C++ 中创建自定义异常

标签 c++ exception

我正在学习 C++,当我尝试创建自己的异常并将它们扔到 Linux 上时,我正在体验。

我创建了一个小型测试项目来测试我的实现,下面是我的异常类头文件。

class TestClass : public std::runtime_error
{
public:
    TestClass(char const* const message) throw();
    virtual char const* what() const throw();
};

异常类的源文件是

using namespace std;

TestClass::TestClass(char const* const message) throw()
    : std::runtime_error(message)
{

}

char const * TestClass::what() const throw()
{
    return exception::what();
}

在我的主应用程序中,我正在调用一个函数,该函数抛出我的异常并在 try/catch 中捕获它,如下所示:

void runAFunctionAndthrow();

/*
 * 
 */
int main(int argc, char** argv) {
    try
    {
        cout << "About to call function" << endl;
        runAFunctionAndthrow();
    }
    catch (TestClass ex)
    {
        cout << "Exception Caught: " << ex.what() << endl;
    }

    return 0;
}

void runAFunctionAndthrow()
{
    cout << "going to run now. oh dear I need to throw an exception" << endl;

    stringstream logstream;
    logstream << "This is my exception error. :(";
    throw TestClass(logstream.str().c_str());
}

当我运行时,我期望得到以下输出:

About to call function

Going to run now. oh dear I need to throw an exception

Exception Caught: This is my exception error. :(

我得到的是

About to call function

going to run now. oh dear I need to throw an exception

Exception Caught: std::exception

请注意最后一行显示 std::exception 而不是我的实际异常消息“这是我的异常错误”。

为什么会这样,它在 Windows 上运行正常,但在 Linux 上却是这样。

从我在各种帖子中看到的内容来看,我所做的是正确的,所以我错过了什么。

最佳答案

你的 what() 返回:

 return exception::what();

std::exception::what() 的返回值为specified as follows :

Pointer to a null-terminated string with explanatory information.

就是这样。仅此而已,仅此而已。您显示的文本当然可以称为“解释性信息”。这是对 what() 的返回值的唯一要求(除了这里不相关的另一个)。

换句话说,C++ 不保证您使用 what() 获得的确切内容。 what() 你看到的就是what() 你得到的,俗话说得好。

如果您希望您的异常以某种方式描述自己,则由您来实现它,作为 what() 的一部分。

关于c++ - 在 C++ 中创建自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41753358/

相关文章:

c++ - 为什么 Boost.Range range_begin/end 自由函数对于 const 和非 const 引用都重载了?

c++读取具有不同文件名的图像集而无需硬编码

c++ - 开始用 C++ 开发数据库接口(interface)的最佳点是什么?

c++ - 模板类型定义?

java - 在 List 上调用 .sort 时出现 AbstractList UnsupportedOperationException

c++ - 如果文件在构造函数中不存在则抛出异常,并在 main() 中创建对象时尝试/捕获它,如果正确 - 开始使用该对象

c++ - 类中的错误/异常捕获

c# - try catch 在 WinForms 应用程序中无法正常工作

java - SimpleDateFormat(无法解析的异常)

c++ - 如何在 Qt Designer UI 文件中清除 QMainWindow 的几何标签