gpt4 book ai didi

c++ - 使用 boost::filesystem 时如何正确处理错误?

转载 作者:行者123 更新时间:2023-11-30 03:02:02 24 4
gpt4 key购买 nike

首先,这是一些代码:

class A
{
public:
A()
{
//...
readTheFile(mySpecialPath);
//...
}

A(boost::filesystem::path path)
{
//...
readTheFile(path);
//...
}

protected:
void readTheFile(boost::filesystem::path path)
{
//First, check whether path exists e.g. by
//using boost::filesystem::exists(path).
//But how to propagate an error to the main function?
}

//...
};
int main(int argc, char **argv)
{
A myClass;

//Some more code which should not be run when A::readTheFile fails
}

有什么好的解决方案可以让主函数知道 A::readTheFile 无法打开文件?我想在打开文件失败时终止执行。

非常感谢!

最佳答案

readTheFile() 抛出异常:

protected:  
void readTheFile(boost::filesystem::path path)
{
//First, check whether path exists e.g. by
//using boost::filesystem::exists(path).
//But how to propagate an error to the main function?
if (/*some-failure-occurred*/)
{
throw std::runtime_error("Failed to read file: " + path);
}
}

...

int main()
{
try
{
A myObj;

//Some more code which should not be run when A::readTheFile fails
}
catch (const std::runtime_error& e)
{
std::cerr << e.what() << "\n";
}

return 0;
}

关于c++ - 使用 boost::filesystem 时如何正确处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10451399/

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