AnyCompiler

Error Handling in C

C has no try, catch, or throw — there's no exception mechanism at all. The standard convention instead is for a function to return a status code (commonly 0 for success, nonzero for a specific kind of failure) and, when there's an actual value to produce, write it through an output pointer parameter instead of returning it directly.

#include <stdio.h>

int safeDivide(int a, int b, int *result) {
    if (b == 0) {
        return -1;
    }
    *result = a / b;
    return 0;
}

int main() {
    int result;
    if (safeDivide(10, 0, &result) == 0) {
        printf("%d\n", result);
    } else {
        printf("Error: division by zero\n");
    }
    return 0;
}
Output
Error: division by zero

That's the foundation of C: no garbage collector, no classes, no exceptions — just functions, structs, pointers, and manual memory management, with the compiler checking far less on your behalf than any other language on this site. Every higher-level abstraction the other courses here provide — garbage collection, RAII, borrow checking, exceptions — exists specifically to automate away a piece of what you've just done by hand. From here, the best next step is practice: pick a small program, and pay close attention to every malloc you write, since in C, free is always your job.

Practice exercise

Write safeDivide(int a, int b, int *result) that returns -1 and leaves *result untouched if b is 0, otherwise stores a / b in *result and returns 0. Call it with (10, 0, &result) and print "Error: division by zero" if it fails.

← const and staticMore lessons coming soon