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

时间:2012-05-04 15:03:17

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

首先,这里有一些代码:

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
}

让main函数知道A :: readTheFile无法打开文件有什么好处?我想在打开文件失败时终止执行。

非常感谢提前!

1 个答案:

答案 0 :(得分:3)

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