I'm developing a large project in C with other team members and we have a disagreement on how "this can never happen" style of errors should be handled. By this I mean error cases that the code currently can never reach, but somebody can modify the code and after the modification it is possible the error case will be reached.
For example, let's say I have a function that returns either 0 on success or -EINVAL if it's given a NULL argument. What I naturally do is:
int err;
struct myctx ctx;
err = callFunction(&ctx);
if (err != 0)
{
abort();
}
or even:
int err;
struct myctx ctx;
err = callFunction(&ctx);
if (err == -EINVAL)
{
abort();
}
else if (err != 0)
{
abort();
}
...to distinguish between the two cases of -EINVAL and unknown error code.
The benefits of this error handling approach are that it is simple to program (few lines of code) and leaves behind a core file that can be used to quickly debug the situation.
However, some team members disagree with this error handling approach because I'm doing an unclean exit and while the code currently can never reach the abort() line it is possible that in the future somebody modifies the code and it reaches the abort() line then. According to them, I should try to do a controlled exit and print the reason to the user. So, I guess instead of this I should do:
int err;
struct myctx ctx;
err = callFunction(&ctx);
if (err == -EINVAL)
{
fprintf(stderr, "Argument was NULL in file %s line %d\n", __FILE__, __LINE__);
exit(1);
}
else if (err != 0)
{
fprintf(stderr, "Error was %d in file %s line %d\n", err, __FILE__, __LINE__);
exit(1);
}
This second error handling strategy has a downside that it does not leave behind a core file that can be used to debug this situation. Also it results in code that has more lines of code.
So, the question is, which strategies exist in C to handle "this can never happen" style of errors? What are their pros and cons? How to decide which to use? Should I do an abort or a controlled exit with a descriptive error message?