Error handling in C involves detecting and managing runtime errors.
int divide(int a, int b, int *result) { if (b == 0) { return -1; // error code } *result = a / b; return 0; // success }
#include <errno.h> #include <stdio.h> FILE *fp = fopen("nonexistent.txt", "r"); if (fp == NULL) { printf("Error opening file: %s\n", strerror(errno)); }
#include <assert.h> void divide(int a, int b) { assert(b != 0); // aborts if b is 0 printf("Result: %d\n", a / b); }
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; }