gpt4 book ai didi

c++ - 异常信息为空

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:01 24 4
gpt4 key购买 nike

我有一个异常类如下:

class FileNotFoundException : public std::exception
{
public:
FileNotFoundException(const char* message) : errorMessage(message){ }
const char* what() const throw() override
{
return this->errorMessage;
}
private:
const char* errorMessage;
};

然后我像这样抛出这个异常:

std::string message = "Message";
throw ::FileNotFoundException(message.c_str());

但是当我尝试使用以下方式处理它时:

try
{
// the code that throws
}
catch(::FileNotFoundException& ex)
{
std::string message = ex.what();
}

字符串 为空。如果有人可以提供帮助,我将不胜感激。

最佳答案

您不能只存储指向消息的指针。尝试将其存储在 std::string 中,或者更好的是,将其传递给父构造函数。在这种情况下,也许最好从 std::runtime_error 继承。

这是一个完整的例子:

#include <iostream>
#include <string>
#include <stdexcept>

class FileNotFoundException : public std::runtime_error
{
public:
FileNotFoundException(const char* message) : std::runtime_error(message)
{
}
};

int main()
{
try {
throw ::FileNotFoundException("oops, something happened");
}
catch(const ::FileNotFoundException& ex) {
std::cout << "Exception: '" << ex.what() << "'" << std::endl;
}
}

编译运行:

$ g++ -W -Wall --std=gnu++11 a.cpp -oa
$ ./a
Exception: 'oops, something happened'

简而言之(没有细节):std::exception 类没有任何构造函数。它只是所有其他异常使用的父类。另一方面,std::runtime_error 有一个为您正确存储消息的构造函数。完整的解释可以在 Difference: std::runtime_error vs std::exception() 中找到。

我认为这种方法比自己定义what() 并使用std::string 来存储消息要好。也就是说,如果您对异常类没有特殊需求。

您还应该查看 C++ exception hierarchy .

关于c++ - 异常信息为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43342006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com