CKTIS / C
error handling — concept C23
C has no exceptions: functions report failure through a return value, output parameter, stream state, or `errno` only when their contract says so. Code must test the signal before using a result, preserve `errno` when needed, release partially acquired resources, and not mistake every boundary value for an error.
Version: C23
Syntax
error handlingC has no exceptions: functions report failure through a return value, output parameter, stream state, or errno only when their contract says so. Code must test the signal before using a result, preserve errno when needed, release partially acquired resources, and not mistake every boundary value for an error.
For a parser, return a status code and store the result only after complete success; strtol requires checking the end pointer, errno == ERANGE, and whether any digit was consumed. With several resources, one cleanup path can release only those actually acquired.
Setting errno = 0 before a call matters only when its documentation says to inspect it; a successful call need not clear an old value. For I/O, distinguish EOF from failure through the result plus feof/ferror, and capture diagnostics before another call changes errno.
Examples
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *end = NULL; errno = 0;
long value = strtol("42x", &end, 10);
printf("%ld %c %d\n", value, *end, errno);
return 0;
}
Result
42 x 0
C has no exceptions: functions report failure through a return value, output parameter, stream state, or `errno` only when their contract says so. Code must test the signal before using a result, preserve `errno` when needed, release partially acquired resources, and not mistake every boundary value for an error.