gpt4 book ai didi

c++ - 如何做我自己的自定义运行时错误类?

转载 作者:可可西里 更新时间:2023-11-01 18:05:43 26 4
gpt4 key购买 nike

我正在尝试做一个简单的自定义 runtime_error。我定义类:

#include <string>
#include <stdexcept>


namespace utils{

class FileNotFoundException: public std::runtime_error{
public:
FileNotFoundException():runtime_error("File not found"){}
FileNotFoundException(std::string msg):runtime_error(msg.c_str()){}
};

};

然后我抛出错误:

bool checkFileExistence( std::string fileName )
{
boost::filesystem::path full_path = boost::filesystem::system_complete(boost::filesystem::path(fileName));
if (!boost::filesystem::exists(full_path))
{
char msg[500];
_snprintf(msg,500,"File %s doesn't exist",fileName.c_str());
throw new FileNotFoundException(msg);
}
}

我使用 try/catch block

    try{
checkFileExistence(fileName);
}
catch(utils::FileNotFoundException& fnfe)
{
std::cout << fnfe.what() << std::endl;
}

运行时错误被正确地抛出为 FileNotFoundException,但从未到达带有 std::cout 的行,并且没有行被写入控制台。

欢迎所有想法。谢谢!

最佳答案

那是因为你在抛出一个指针。只需执行:throw FileNotFoundException(msg);

无论何时您使用指针,除非您将它放入容器/包装器中,否则您可能没有做正确的事情。

关于c++ - 如何做我自己的自定义运行时错误类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3688347/

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