【问题标题】:How to correctly handle errors when using boost::filesystem?使用 boost::filesystem 时如何正确处理错误?
【发布时间】:2012-05-04 15:03:17
【问题描述】:

首先,这里有一些代码:

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 无法打开文件有什么好的解决方案?我想在打开文件失败时终止执行。

非常感谢!

【问题讨论】:

  • throwcatch 异常?

标签: c++ boost file-io exception-handling


【解决方案1】:

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;
}

【讨论】:

  • 谢谢!我已经尝试过这种方法,但使用boost::filesystem::filesystem_error 而不是std::runtime_error 并在catch 子句中添加了return 1;。当我运行程序以便引发异常时,what() 方法正确输出,但随后程序只是挂起而不是根据return 1; 终止。怎么了? (VC++ 2010,调试版本)
  • 感谢您的帮助。有用。程序挂起与 Boost 或此处显示的代码无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
相关资源
最近更新 更多