Lesson 105 +10 XP

Error Handling in C

Error Handling in C

C has no built-in exceptions. Programs handle errors by checking return values.

The style

C functions return special values to signal errors:

  • NULL - when a pointer couldn't be created.
  • -1 - a classic error marker.
  • 0 - often means success (main returns 0).

A real pattern

FILE *file = fopen("missing.txt", "r");
if (file == NULL) {
    printf("Could not open the file!");
    return 1;
}

Returning an error code

int divide(int a, int b) {
    if (b == 0) {
        return -1;   // error signal
    }
    return a / b;
}

Key mindset

C assumes you check the returns. Skip the checks and errors slip through silently.

TL;DR

  • No try/throw in C.
  • Use return values to signal errors.
  • Check fopen, malloc, and system calls.
  • Always test for failure before using results.