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?