When to use strerror method

90 views Asked by At

I recently found this legacy code that uses strerror() method to find out why a file operation failed instead of using the exception object.

try
{
    boost::filesystem::path src(...);
    boost::filesystem::path dst(...);
    boost::filesystem::copy_file(src, dst);
}
catch (const boost::filesystem::filesystem_error& ex)
{
   std::cout << "Failed to copy files. " << strerror(errno) << std::endl;
}

In one scenario the hard disk was full which caused the file copy to fail and strerror() returned "No Error". The exception object provided a correct "There is not enough space on the disk" error.

Before making any changes to the code I wanted to understand strerror.

  1. Is it "only" C runtime libraries that register errors "in" strerror?
  2. Are there any scenarios where strerror will provide a better error message than for example a filesystem exception?
  3. If we are not calling any C runtime functions directly, do we have any reason to use strerror()?

Using boost 1.71 on Windows and Linux

Appreciate any input

1

There are 1 answers

0
Nikos Athanasiou On

copy_filehas two overloads:

  • One that throws and doesn't take an error code parameter
bool copy_file(const path& from, const path& to);
  • One that does not throw and accepts an error code parameter
bool copy_file(const path& from, const path& to, system::error_code& ec);

This applies both to the boost and standard library implementations. In the snippet you provide, no error_code information is passed to the call so all error reporting should be done using the exception object.

That said, to address specific questions:

  1. Is it "only" C runtime libraries that register errors "in" strerror?

No. Case in point, for the standard library version:

"The overload taking a std::error_code& parameter sets it to the OS API error code if an OS API call fails, and executes ec.clear() if no errors occur."

  1. Are there any scenarios where strerror will provide a better error message than for example a filesystem exception?

Hardly, because the exception message is essentially a concatenation of "from as the first path argument, to as the second path argument, and the OS error code as the error code argument".

  1. If we are not calling any C runtime functions directly, do we have any reason to use strerror()?

It's not about "message richness". There are some implications with thread safety (read up on the provided links) but the non throwing versions are to be used where exceptions are not a fitting choice e.g.:

  • restricted environments,
  • banned from usage (due to coding standard or company policy)
  • the existing codebase does not use exceptions and you don't want to code against the grain
  • Operation of the platform or application makes copy failure probability high enough to not be considered an exceptional case.