C•Error Handling
C Error Handling: Return Codes, errno, and perror
Since C has no exceptions, error handling relies on return status codes and the global errno variable from <errno.h>.
Syntax
#include <errno.h>
if (res == -1) {
perror("Operation failed");
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| errno | Global Variable | Set by system calls when an error occurs. |
| perror(str) | Function | Prints error message string corresponding to current errno. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C locally:
#include <stdio.h>
#include <errno.h>
#include <string.h>
int safeDivide(int numerator, int denominator, int* result) {
if (denominator == 0) {
return -1; // Error code for invalid division
}
*result = numerator / denominator;
return 0; // Success
}
int main(void) {
int res = 0;
// 1. Success case
if (safeDivide(100, 5, &res) == 0) {
printf("100 / 5 = %d\n", res);
}
// 2. Error case
if (safeDivide(50, 0, &res) != 0) {
printf("[ERROR] Division by zero prevented cleanly!\n");
}
return 0;
}Expected Output:
100 / 5 = 20 [ERROR] Division by zero prevented cleanly!
How It Works: Step-by-Step
- Lines 5-11: safeDivide returns status integer (0 = success, -1 = error).
- Lines 16-24: Caller checks return code before using result.
Key Concepts
- Idiomatic C functions return 0 on success and negative values or NULL on error.
- The actual computation result is returned via output pointer parameters.
Common Mistake: Ignoring function return codes
Ignoring return codes leads to operating on invalid data after a failure occurred.
❌ Incorrect
safeDivide(50, 0, &res);
printf("%d", res); // Uses uninitialized/invalid result!✅ Correct
if (safeDivide(50, 0, &res) == 0) { printf("%d", res); }Related C Tutorials & Compiler
C Function Prototyping and Execution Frame Call Stacks
Declare forward function prototypes, understand stack activation frames, and manage pass-by-value vs pointer frame mutations in C.
C File I/O: fopen, fread, fwrite, and fclose
Read and write disk streams using standard C FILE* handles, fopen, and fclose.
C Pointers: Memory Addresses, Dereferencing (*), and Pointer Arithmetic
Master pointers in C: address-of (&), dereferencing (*), pass-by-reference simulation, and pointer math.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.