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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41753358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:28:06  来源:igfitidea点击:

Creating custom exceptions in C++

c++exception

提问by Boardy

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

我正在学习 C++,当我尝试创建自己的异常并在 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();
};

The source file for the exception class is

异常类的源文件是

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:

在我的主应用程序中,我正在调用一个函数,该函数抛出我的异常并在 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());
}

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

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

About to call function

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

Exception Caught: This is my exception error. :(

即将调用函数

现在要跑了。哦,亲爱的,我需要抛出异常

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

Instead what I am getting is

相反,我得到的是

About to call function

going to run now. oh dear I need to throw an 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".

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

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

为什么会这样,它在 Windows 上可以正常工作,但在 Linux 上却可以。

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

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

采纳答案by Sam Varshavchik

Your what()returns:

您的what()回报:

 return exception::what();

The return value from std::exception::what()is specified as follows:

从返回值std::exception::what()规定如下

Pointer to a null-terminated string with explanatory information.

指向带有解释信息的以空字符结尾的字符串的指针。

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).

就是这样。没有更多,没有别的。您显示的文本当然有资格作为“解释性信息”。这是返回值的唯一要求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.

换句话说,C++ 不保证您使用what(). what()你看到的就是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().

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

回答by andrgolubev

You need your own implementation of what() method or use std::runtime_error::what()as written in comments

您需要自己实现 what() 方法或使用std::runtime_error::what()注释中所写的

Say:

说:

class TestClass : public std::runtime_error
{
    std::string what_message;
public:
    const char* what() override
    {
        return what_message.c_str();
    }
};

Also, better use noexceptinstead of throw()and only after you read about them - link.

此外,更好地使用noexcept而不是throw()并且仅在您阅读它们之后使用- link

And in your try-catch:

在你的 try-catch 中:

catch (const TestClass& myException)

Instead of catch(TestClass myException)- otherwise you do an implicit copy which can potentially result in an exception throw. It also breaks the polymorphism: if you want to catchpure virtual interfaceimplementation instance, you would need to use a reference.

而不是 catch(TestClass myException)- 否则您会进行隐式复制,这可能会导致异常抛出。它也打破了多态性:如果你想catchpure virtual interface实现实例,你需要使用引用。

回答by Furkan Fidan

You need a way to specify a custom error message to std::exception which afaik is not allowed. See thisfor a possible solution.

您需要一种将自定义错误消息指定给 std::exception 的方法,这是不允许的。请参阅以获取可能的解决方案。