How should "this can never happen" style of errors in C be handled? -
i'm developing large project in c other team members , have disagreement on how "this can never happen" style of errors should handled. mean error cases code can never reach, can modify code , after modification possible error case reached.
for example, let's have function returns either 0 on success or -einval if it's given null argument. naturally 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 2 cases of -einval , unknown error code.
the benefits of error handling approach simple program (few lines of code) , leaves behind core file can used debug situation.
however, team members disagree error handling approach because i'm doing unclean exit , while code can never reach abort() line possible in future modifies code , reaches abort() line then. according them, should try controlled exit , print reason user. so, guess instead of should do:
int err; struct myctx ctx; err = callfunction(&ctx); if (err == -einval) { fprintf(stderr, "argument null in file %s line %d\n", __file__, __line__); exit(1); } else if (err != 0) { fprintf(stderr, "error %d in file %s line %d\n", err, __file__, __line__); exit(1); }
in opinion, second error handling strategy worse because not leave behind core file can used debug situation. furthermore, results in code has more lines of code.
so, question is, how should "this can never happen" style of errors handled in c? should abort or controlled exit descriptive error message?
on principle, should handle errors , generate explanatory description possible user. proper thing do, call honte in japan.
however, in practice, unexplained abort()
in first example because faster write. consequence of applications, when fail, exit miserably. example, when microsoft word crashes, message user "word has encountered problem , exit." or effect. many applications give no message @ terminate.
proper programming code called negative path. not should every possible failure generate meaningful text message, failure returns , percolates backwards through call chain, each calling function should add context , relevant parameters front of message. end message user should this:
while attempting initialize: while attempting load configuration file @ [c:\user\data\configuration.ini]: failed read line 453: invalid parameter value 'numredirects' (out of bounds): -43
in error message see each function receiving error inserts context @ beginning of string followed colon , returns failure function called it. net result shows important information (the file being read, line being parsed, parameter being loaded, invalid value supplied parameter). fully explains user (or developer) problem was.
Comments
Post a Comment