21. Error Handling, errno & Non-Local Jumps (setjmp/longjmp)
🔴 Difficulty: Advanced | System Error Codes, Defensive Return Values & Exception Recovery
📖 Definition
Because C does not feature built-in object-oriented try/catch exception handling, error handling relies on returning diagnostic status codes, inspecting the global system variable errno (from <errno.h>), and formatting error descriptions via perror() or strerror(). For deep call stack recovery, setjmp() and longjmp() (from <setjmp.h>) perform non-local stack jumps.
🎯 Why It Is Used
- Fault-Tolerant Systems: Handling file-not-found, out-of-memory, or socket timeout errors gracefully without crashing.
- System OS Error Inspection: Converting numerical system error codes (like
ENOENTorENOMEM) into human-readable messages. - Deep Exception Recovery: Returning execution immediately to an outer error recovery loop across multiple nested function call frames.
⚙️ How It Works: errno & System Calls
When a standard C C-library or OS system call fails (e.g., fopen() returning NULL), it sets the thread-local global integer variable errno to an error code constant:
| Error Code Constant | Numeric Code | Meaning Description |
|---|---|---|
ENOENT | 2 | No such file or directory. |
EACCES | 13 | Permission denied. |
ENOMEM | 12 | Out of memory (cannot allocate heap space). |
EDOM | 33 | Mathematics domain argument error (e.g. sqrt(-1)). |
ERANGE | 34 | Result value numerical range overflow. |
📝 Syntax
#include <stdio.h>
#include <errno.h>
#include <string.h>
// 1. Inspecting errno & Printing Description
FILE *fp = fopen("missing.txt", "r");
if (fp == NULL) {
perror("fopen failed"); // Prints: "fopen failed: No such file or directory"
printf("errno code: %d | Description: %s\n", errno, strerror(errno));
}
// 2. Non-Local Exception Recovery (<setjmp.h>)
#include <setjmp.h>
jmp_buf recovery_env;
if (setjmp(recovery_env) == 0) {
// Normal execution branch
} else {
// Jumped recovery branch after error!
}
🔀 Defensive Status Return Pattern
Functions should return explicit status codes (e.g. 0 or enum ErrorCode for success, negative non-zero values for failure) while returning computed results via output pointers.
🌱 Beginner Example: Checking errno & perror()
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(void) {
// Reset errno before system call
errno = 0;
FILE *fp = fopen("/invalid_dir/non_existent_file.txt", "r");
if (fp == NULL) {
printf("System Call Failed! errno = %d\n", errno);
perror("Error Detail (perror)");
printf("Error Message (strerror): %s\n", strerror(errno));
return 1;
}
fclose(fp);
return 0;
}
🌼 Intermediate Example: Defensive Status Code Return Pattern
#include <stdio.h>
typedef enum {
ERR_SUCCESS = 0,
ERR_DIVISION_BY_ZERO = -1,
ERR_NULL_POINTER = -2
} Status;
Status divide_safely(int numerator, int denominator, int *out_result) {
if (out_result == NULL) {
return ERR_NULL_POINTER;
}
if (denominator == 0) {
return ERR_DIVISION_BY_ZERO;
}
*out_result = numerator / denominator;
return ERR_SUCCESS; // Success
}
int main(void) {
int res;
Status status = divide_safely(10, 0, &res);
if (status == ERR_SUCCESS) {
printf("Result: %d\n", res);
} else if (status == ERR_DIVISION_BY_ZERO) {
fprintf(stderr, "Calculation Error: Division by zero caught defensively!\n");
}
return 0;
}
🌲 Advanced Example: Deep Stack Recovery with setjmp/longjmp
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
jmp_buf exception_buffer;
void nested_subroutine(int val) {
printf("[Nested] Processing value: %d\n", val);
if (val < 0) {
printf("[Nested] Fatal error detected! Triggering non-local jump...\n");
longjmp(exception_buffer, 999); // Jumps back to setjmp site!
}
}
void outer_pipeline(void) {
nested_subroutine(10);
nested_subroutine(-5); // Triggers error!
nested_subroutine(20); // Never reached!
}
int main(void) {
// setjmp returns 0 on initial setup call
int jump_code = setjmp(exception_buffer);
if (jump_code == 0) {
printf("=== Starting Pipeline Execution ===\n");
outer_pipeline();
} else {
// Returned via longjmp(exception_buffer, 999)
printf("=== Exception Caught! Error Code: %d ===\n", jump_code);
printf("System recovered safely back to main().\n");
}
return 0;
}
🔍 Line-by-Line Explanation
perror("Error Detail");: Prints the prefix string followed by a colon and the human-readable string corresponding to the currenterrno.strerror(errno);: Returns a read-only string pointer describing theerrnocode value.setjmp(exception_buffer): Saves the current CPU registers and stack frame state, returning 0 on setup.longjmp(exception_buffer, 999): Restores saved registers, unwinding nested call stack frames instantly and returning control to thesetjmpsite with code 999.
💻 Expected Terminal Output
System Call Failed! errno = 2
Error Detail (perror): No such file or directory
Error Message (strerror): No such file or directory
Calculation Error: Division by zero caught defensively!
=== Starting Pipeline Execution ===
[Nested] Processing value: 10
[Nested] Processing value: -5
[Nested] Fatal error detected! Triggering non-local jump...
=== Exception Caught! Error Code: 999 ===
System recovered safely back to main().
⚠️ Common Mistakes & Pitfalls
- Not Resetting
errnoBefore Calls: C library functions seterrnoon error, but NEVER reset it to 0 on success. Always seterrno = 0;before invoking the function! - Using
longjmp()to Inactive Stack Frames: Callinglongjmp()after the function containingsetjmp()has already returned results in undefined behavior and crashes.
📌 Important Rules & Limitations
- Check status return codes or
errnoafter system calls. - Always set
errno = 0;before calling functions whose error state you intend to inspect. - Use
setjmp()/longjmp()sparingly for deep exception recovery.
🌐 Multilingual Explanation: English
C error handling uses return status codes and the thread-local errno global variable. Format errors with perror() or strerror(), and use setjmp()/longjmp() for non-local stack recovery.
🌐 Multilingual Explanation: Hindi (Roman Script)
C mein exception try/catch nahi hota. Error handling ke liye functions return status code dete hain aur system errors errno mein store hote hain. Error details dekhne ke liye perror() ka use karein.
🌐 Multilingual Explanation: Marathi (Roman Script)
C language madhye error handling status codes aani errno varni hote. Error message print karnyasathi perror() vapratat.
❓ Practice Questions
- Why must
errnobe set to 0 before executing a system call? - What is the difference between
perror()andstrerror()? - How does
setjmp()differ from a standardgotostatement?
🚀 Practical Coding Challenge
Write a C program named safe_file_reader.c that attempts to open a file passed as a command line argument, checks errno if opening fails, and uses strerror(errno) to log custom error messages to stderr.
🧭 Navigation & Breadcrumbs
← Previous: 20. Multi-File Projects | Master Syllabus | Next Module: 22. GDB & Sanitizers →