Search code examples
c++exceptionfilesystems

std::filesystem::file_size() and C++ exceptions


First, I'm assuming it is normal to get C++ exceptions when calling std::filesystem::file_size() for a path that doesn't exist. But I'm wondering why this happens, and/or what I'm supposed to do to avoid the exceptions?

Generally, I'm under the impression that an exception means I'm taking a wrong turn as the programmer. Is that the case here? From my experience, it seems like most of the file utilities (in Visual Studio at least) throw exceptions over these (seemingly trivial) things, even though you'd expect these conditions to be part of their normal operation and behavior.

Often, I'm calling these functions because I'm unsure about the file and weather it exists. But should I be calling another function to make sure it exists before I request its size, such as std::filesystem::exists()? Or is there some way to disable these "minor" exceptions? I know I can disable the exceptions in my compiler so that I do not detect them, but they are still being generated in this case. Any advice on this subject would be appreciated.


Solution

  • Use the nonthrowing version of std::filesystem::file_size:

    std::error_code theErrorCode;
    auto theSize = std::filesystem::file_size(thePath, theErrorCode); // this won't throw
    if (theErrorCode)
    {
       // handle error
    }
    else
    {
       // handle success, theSize contains the file size
    }
    

    or wrap it into your own function, like for example:

    std::uintmax_t myfilesize(const std::filesystem::path& path, std::error_code& error)
    {
      try
      {
        error.assign(0, std::generic_category());
        return std::filesystem::file_size(path);
      }
      catch (std::filesystem::filesystem_error& e)
      {
        error = e.code();  
        return 0;
      }
    }