Error checking in C is a task that is very verbose and makes the code unreadable. In C++ you have exceptions, but when I use C++ to call C functions, the headaches come back. I wish there was a "syscalls wrapper for C++" where all the functions have the same names and parameters, but where errors are turned into exceptions and that's all. That would be game changing.
Trying to solve that verbosity problem when interacting with C functions/syscalls from C++, I came up with the following solution (simplified here):
void ko(char const* doingwhat) // or ko_check or whatever
{
if (errno != 0)
throw std::runtime_error(doingwhat);
}
void some_method()
{
errno = 0;
int fd = open(blablabla, blablabla); ko("opening the file");
void* ptr = mmap(blablabla, blablabla); ko("mmaping it");
struct stat st; fstat(fd, &st); ko("getting stats");
// etc etc etc
}
The method is to directly ignore return values and check errno instead. Since errno is thread local and can only change if there's an error in a libc call, with setting errno = 0 at the beginning of your method would be enough.
In C doing that would be pointless (or at least not that benefitial) because you cannot get rid of returning in case of error anyway, and that's why I think I have never seen that kind of approach mentioned in any discussions about error handling.
Is there any important pitfall in that approach of mine? Can errno be != 0 in surprising situations? Anything to be aware of? That fact that I have never seen this "approach" discussed anywhere makes me wonder if there's any good reason for it, because I don't see any.
NOTE: Of course, you have to be careful about functions that set errno in conditions that might be ok for you. Know the functions you use very well and don't let the habit of just calling ko cause you forget about checking the man pages of the functions you use, continuously.
errnois undefined unless the called function returned with a failure indicator. There are a few exceptions, but the functions you use are not in that (very) short list.errno.