Back to Blog

C in 100 Seconds: Error Handling

Daryl WongDaryl Wong

Video: C in 100 Seconds: Error Handling — errno, perror, strerror | Episode 39 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Error Handling in C

C has no exceptions. Errors are handled through return values, a global variable called errno, and helper functions.

perror — Quick Error Messages

FILE *f = fopen("/tmp/no_such_file.txt", "r");
if (f == NULL) {
  perror("fopen failed");
  // prints: fopen failed: No such file or directory
}

perror prints your message followed by the system error description. Simplest way to report what went wrong.

errno and strerror — Error Details

FILE *f2 = fopen("/etc/master.passwd", "r");
if (f2 == NULL) {
  printf("errno: %d\n", errno);        // 13
  printf("error: %s\n", strerror(errno)); // Permission denied
}

errno holds the error code from the last failed call. strerror converts it to a human-readable string. Reset errno to zero before each call to avoid stale values.

stderr — Error Output Stream

fprintf(stderr, "Error: division by zero\n");

stderr is a separate output stream from stdout. It is unbuffered — errors show immediately. Use it for error messages so they do not mix with normal program output.

Return Codes

Return zero for success, nonzero for failure. This is the universal convention in C — the caller checks the return value to know if the operation succeeded.

Student Code

Try it yourself: episode39/errors.c