Lesson 108 +10 XP

Error Numbers and errno

Error Numbers and errno

The global variable errno carries the last error's code. It lives in <errno.h>.

Set and read

#include <errno.h>
#include <math.h>

double result = sqrt(-1);
if (errno == EDOM) {
    printf("Domain error: sqrt of negative\n");
}
  • errno is set by library functions after an error.
  • Never assume it stays 0 nor reset.

Common errors

  • EDOM - math domain error.
  • ERANGE - result out of range.
  • ENOMEM - out of memory.

The pattern: check right after a call

Set errno=0 first, call, then check:

errno = 0;
double v = strtod(text, NULL);
if (errno != 0) {
    printf("Conversion failed\n");
}

TL;DR

  • errno holds the last error number.
  • EDOM, ERANGE, ENOMEM are three common ones.
  • Reset errno=0 before a critical call.
  • Check immediately after the call.