从boost :: filesystem :: is_directory中捕获异常

时间:2011-07-14 17:13:50

标签: c++ boost exception-handling

我目前正在从boost :: filesystem :: is_directory中捕获错误,并通过在异常上调用“what()”向用户显示错误。这给出了失败的原因,但错误对用户来说很奇怪。例如:

  

boost :: filesystem :: is_directory:访问被拒绝

如何捕获提升错误并找出实际原因,以便显示更好的错误消息?

1 个答案:

答案 0 :(得分:17)

通过“更好的错误消息”,您的意思是

#include <iostream>
#include <boost/filesystem.hpp>
int main()
{
    boost::filesystem::path p("/proc/1/fd/1");
    try {
       boost::filesystem::is_directory(p);
    } catch(const boost::filesystem::filesystem_error& e)
    {
       if(e.code() == boost::system::errc::permission_denied)
           std::cout << "Search permission is denied for one of the directories "
                     << "in the path prefix of " << p << "\n";
       else
           std::cout << "is_directory(" << p << ") failed with "
                     << e.code().message() << '\n';
    }
}