HOME HTML EDITOR C JAVA PHP

C Error: Detecting and Managing Failures

Because C is a low-level language, it doesn't automatically "throw" an error when something goes wrong. Instead, most C functions return a special value (like -1 or NULL) to signal a problem. It is the programmer's job to check these values and decide what to do next.

1. The Global errno Variable

When a standard library function fails, it typically sets a global integer variable called errno (Error Number). This variable holds a code that represents the specific reason for the failure.

To use errno, you must include the <errno.h> header.

Common Error Codes

2. Reporting Errors: perror() and strerror()

Since numeric codes like "2" or "33" aren't helpful to users, C provides two functions to translate errno into a human-readable string.

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

int main() {
    FILE *fptr = fopen("non_existent.txt", "r");

    if (fptr == NULL) {
        // Method 1: perror
        perror("Error opening file");

        // Method 2: strerror
        printf("Error detail: %s\n", strerror(errno));
    }
    return 0;
}

3. Exit Status: EXIT_SUCCESS vs EXIT_FAILURE

When a program terminates, it sends an exit status to the Operating System. By convention, 0 means success, and any non-zero value means an error occurred.

In <stdlib.h>, two constants are defined to make this explicit:

4. Defensive Programming: Divide by Zero

C does not have a specific errno for division by zero; on many systems, this will simply crash the program with a "Floating Point Exception." You must check the divisor manually before performing the operation.

int a = 10, b = 0;
if (b == 0) {
    fprintf(stderr, "Division by zero error! Exiting...\n");
    exit(EXIT_FAILURE);
}
int result = a / b;

5. Error Handling Strategies

Professional C developers follow these strategies to build robust software:

Strategy Description
Return Value Check Always check if malloc returned NULL or if fopen failed.
Use stderr Print error messages to the "Standard Error" stream instead of stdout.
Graceful Exit Free memory and close open files before calling exit().
Reset errno Since errno is never reset to 0 by the system, clear it manually (errno = 0;) before a critical call.

6. Signals: Handling Runtime Interrupts

For errors that are more severe (like Segment Faults or hitting Ctrl+C), C uses Signals. Using <signal.h>, you can write a "signal handler" function to catch these events and shut down the program cleanly.

Pro Tip: When writing a library in C, never print errors directly to the screen. Instead, return an error code to the user of your library. This allows the developer using your code to decide how to present the error to the end user.