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 ENOENT or ENOMEM) 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
ENOENT2No such file or directory.
EACCES13Permission denied.
ENOMEM12Out of memory (cannot allocate heap space).
EDOM33Mathematics domain argument error (e.g. sqrt(-1)).
ERANGE34Result 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 current errno.
  • strerror(errno);: Returns a read-only string pointer describing the errno code 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 the setjmp site 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 errno Before Calls: C library functions set errno on error, but NEVER reset it to 0 on success. Always set errno = 0; before invoking the function!
  • Using longjmp() to Inactive Stack Frames: Calling longjmp() after the function containing setjmp() has already returned results in undefined behavior and crashes.

📌 Important Rules & Limitations

  • Check status return codes or errno after 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

  1. Why must errno be set to 0 before executing a system call?
  2. What is the difference between perror() and strerror()?
  3. How does setjmp() differ from a standard goto statement?

🚀 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 →