Skip to content

C Error Handling

Error handling in C involves detecting and managing runtime errors.

1. Return Codes

c
int divide(int a, int b, int *result) {
    if (b == 0) {
        return -1;  // error code
    }
    *result = a / b;
    return 0;  // success
}

2. errno Variable

c
#include <errno.h>
#include <stdio.h>

FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
    printf("Error opening file: %s\n", strerror(errno));
}

3. assert Macro

c
#include <assert.h>

void divide(int a, int b) {
    assert(b != 0);  // aborts if b is 0
    printf("Result: %d\n", a / b);
}

4. Custom Error Handling

c
typedef enum {
    SUCCESS,
    ERROR_NULL_POINTER,
    ERROR_INVALID_PARAMETER,
    ERROR_FILE_NOT_FOUND
} ErrorCode;

ErrorCode process_data(int *data) {
    if (data == NULL) {
        return ERROR_NULL_POINTER;
    }
    // process data
    return SUCCESS;
}

Content is for learning and research only.