HOME HTML EDITOR C JAVA PHP

C Error Handling:

Unlike modern languages like Java or Python, C does not have built-in "Exceptions" (try/catch). In C, Error Handling is done manually by checking return values of functions and using specific system variables to identify what went wrong.

1. Return Values as Error Signals

Most C functions return a specific value to indicate an error. Usually, a function returns -1 or NULL if it fails, and 0 or a valid pointer if it succeeds.

2. The errno Variable

When a system call fails, it sets a global variable called errno. This is an integer representing the specific error code. To use it, you must include the <errno.h> header.

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

extern int errno;

int main() {
    FILE *fp = fopen("nonexistent.txt", "r");
    if (fp == NULL) {
        printf("Error Value: %d\n", errno);
        printf("Error Message: %s\n", strerror(errno));
    }
    return 0;
}

3. perror() and strerror()

Since error numbers (like 2 or 12) are hard to understand, C provides two functions to convert errno into human-readable text:

Function Description
perror("msg") Prints your custom message followed by the system error description.
strerror(errno) Returns a pointer to the textual string representation of the current errno.

4. Common Error Codes

While there are many error codes, these are the ones you will encounter most frequently:

5. Exit Status: EXIT_SUCCESS and EXIT_FAILURE

To make your code more readable, you can use macros from <stdlib.h> when terminating your program.

#include <stdlib.h>

if (critical_error) {
    exit(EXIT_FAILURE); // Equivalent to exit(1)
} else {
    exit(EXIT_SUCCESS); // Equivalent to exit(0)
}

6. Defensive Programming Tips

Pro Tip: Use stderr instead of stdout for printing error messages. This ensures errors are visible even if the user redirects the standard output to a file! fprintf(stderr, "Error occurred!\n");