本文介绍了在C ++中创建自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++,在尝试创建自己的异常并将其扔到Linux上时遇到了问题。

I am learning C++ and I am experiencing when I try and create my own exception and throw them on Linux.

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

I've created a small test project to test my implementation and below is my exception class header file.

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();
}

在我的主应用程序中,我正在调用一个引发异常并捕获的函数

In my main app, I am calling a function which throws my exception and catches it in a try/catch as follows:

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());
}

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

When I run I'm expecting to get the following output:

现在要运行。亲爱的我需要抛出一个异常

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

异常捕获:这是我的异常错误。:(

Exception Caught: This is my exception error. :(

相反,我得到的是

现在要运行。哦,亲爱的我需要抛出一个异常

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

捕获到的异常:std :: exception

Exception Caught: std::exception

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

Notice the last line it says std::exception instead of my actual exception message "This is my exception error".

这是为什么,它在Windows上可以正常运行,但在Linux上可以。

Why is this, it works OK on Windows but on Linux it does this.

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

From what I've seen on various posts what I've done is correct so what am I missing.

推荐答案

您的 what()返回:

 return exception::what();

std :: exception :: what()的返回值是:

就是这样。仅此而已。您显示的文字当然可以视为解释性信息。这是返回值 what()的唯一要求(除了另一个与此处不相关的值)。

That's it. Nothing more, nothing else. The text you're showing certainly qualifies as an "explanatory information". And this is the only requirement for the return value of what() (except for one other one which is not germane here).

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

In other words, C++ does not guarantee the exact contents of what you get with what(). what() you see is what() you get, as the saying goes.

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

If you want your exception to describe itself, in some way, it's up to you to implement that, as part of your what().

这篇关于在C ++中创建自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:54