C++ 使用boost::filesystem时如何正确处理错误?
首先,这里有一些代码:C++ 使用boost::filesystem时如何正确处理错误?,c++,boost,file-io,exception-handling,C++,Boost,File Io,Exception Handling,首先,这里有一些代码: class A { public: A() { //... readTheFile(mySpecialPath); //... } A(boost::filesystem::path path) { //... readTheFile(path); //... } protected: void readTheFi
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?
}
//...
};
让主函数知道a::readTheFile无法打开该文件的好解决方案是什么?我想在打开文件失败时终止执行
非常感谢 HavereadTheFile()
引发异常:
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;
}
受保护:
void readTheFile(boost::filesystem::path)
{
//首先,检查路径是否存在,例如通过
//使用boost::filesystem::exists(路径)。
//但是如何将错误传播到主函数?
如果(/*发生某些故障*/)
{
抛出std::runtime_错误(“读取文件失败:+path”);
}
}
...
int main()
{
尝试
{
myObj;
//当::readTheFile失败时不应运行的其他代码
}
捕获(const std::runtime_error&e)
{
std::cerrthrow
和catch
异常?谢谢!我已经尝试过这种方法,但使用了boost::filesystem::filesystem\u error
而不是std::runtime\u error
并在catch
-子句中添加了return 1;
。当我运行程序以便引发异常时,what()
方法输出正确,但程序只是挂起,而不是根据返回1;
终止。出了什么问题?(VC++2010,调试版本)感谢您的帮助。它可以工作。程序挂起与Boost或此处显示的代码无关。
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;
}