Tutorials Logic, IN info@tutorialslogic.com

C Error Handling errno, perror, strerror: Causes, Fixes, Examples & Interview Tips

C Error Handling errno, perror, strerror

C Error Handling errno, perror, strerror is an important C Language topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem C Error Handling errno, perror, strerror solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of C Error Handling errno, perror, strerror should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

C Error Handling errno perror strerror should be studied as a practical C Language lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the c-language > error-handling page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

Error Handling in C

Unlike C++ or Java, C has no built-in exception mechanism. Error handling in C is done through:

  • Return values - functions return a special value (e.g., -1, NULL, 0) to signal failure.
  • errno - a global integer variable set by system calls and library functions when an error occurs.
  • perror() - prints a human-readable error message to stderr.
  • strerror() - returns the error message string for a given errno value.

Return Value Pattern

The most fundamental C error handling pattern: check the return value of every function that can fail.

Checking Return Values

Checking Return Values
#include <stdio.h>
#include <stdlib.h>

// Function returns -1 on error, result on success
int divide(int a, int b, int *result) {
    if (b == 0) {
        return -1;  // error code
    }
    *result = a / b;
    return 0;  // success
}

int main() {
    int result;

    // Success case
    if (divide(10, 2, &result) == 0) {
        printf("10 / 2 = %d\n", result);
    } else {
        printf("Error: division failed\n");
    }

    // Error case
    if (divide(10, 0, &result) == 0) {
        printf("10 / 0 = %d\n", result);
    } else {
        printf("Error: cannot divide by zero\n");
    }

    // malloc returns NULL on failure
    int *arr = (int*)malloc(1000000000 * sizeof(int));  // huge allocation
    if (arr == NULL) {
        fprintf(stderr, "Error: memory allocation failed\n");
        return EXIT_FAILURE;
    }
    free(arr);

    return EXIT_SUCCESS;
}

errno, perror() and strerror()

errno is set by system calls when they fail. Always check errno immediately after a failed call - the next function call may overwrite it.

errno Code Value Meaning
ENOENT 2 No such file or directory
EACCES 13 Permission denied
ENOMEM 12 Out of memory
EINVAL 22 Invalid argument
ERANGE 34 Result out of range

errno, perror() and strerror()

errno, perror() and strerror()
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main() {
    // Try to open a file that doesn't exist
    FILE *fp = fopen("nonexistent.txt", "r");

    if (fp == NULL) {
        // errno is set by fopen on failure
        printf("errno value: %d\n", errno);

        // perror: prints "prefix: error message" to stderr
        perror("fopen failed");

        // strerror: returns the error string
        printf("Error: %s\n", strerror(errno));
    }

    // Reset errno before next call
    errno = 0;

    // Math error: log of negative number
    #include <math.h>
    double result = sqrt(-1.0);
    if (errno == EDOM) {
        perror("sqrt(-1)");  // sqrt(-1): Numerical argument out of domain
    }

    return 0;
}

/*
Output:
errno value: 2
fopen failed: No such file or directory
Error: No such file or directory
*/

Custom Error Handling Pattern

A clean pattern for larger programs: define your own error codes and a centralized error handler.

Custom Error Codes Pattern

Custom Error Codes Pattern
#include <stdio.h>
#include <stdlib.h>

// Custom error codes
typedef enum {
    ERR_OK       = 0,
    ERR_NULL_PTR = 1,
    ERR_DIV_ZERO = 2,
    ERR_OVERFLOW = 3,
    ERR_IO       = 4
} ErrorCode;

// Error message lookup
const char* errorMessage(ErrorCode code) {
    switch (code) {
        case ERR_OK:       return "Success";
        case ERR_NULL_PTR: return "Null pointer";
        case ERR_DIV_ZERO: return "Division by zero";
        case ERR_OVERFLOW: return "Integer overflow";
        case ERR_IO:       return "I/O error";
        default:           return "Unknown error";
    }
}

// Function using custom error codes
ErrorCode safeDivide(int a, int b, int *out) {
    if (out == NULL) return ERR_NULL_PTR;
    if (b == 0)      return ERR_DIV_ZERO;
    *out = a / b;
    return ERR_OK;
}

int main() {
    int result;
    ErrorCode err;

    err = safeDivide(10, 2, &result);
    if (err == ERR_OK) printf("10/2 = %d\n", result);
    else printf("Error: %s\n", errorMessage(err));

    err = safeDivide(10, 0, &result);
    if (err == ERR_OK) printf("10/0 = %d\n", result);
    else printf("Error: %s\n", errorMessage(err));  // Error: Division by zero

    err = safeDivide(10, 2, NULL);
    if (err == ERR_OK) printf("result = %d\n", result);
    else printf("Error: %s\n", errorMessage(err));  // Error: Null pointer

    return 0;
}

Detailed Learning Notes for C Error Handling errno, perror, strerror

When studying C Error Handling errno, perror, strerror, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In C Language, C Error Handling errno, perror, strerror becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

C Error Handling errno perror strerror C review example

C Error Handling errno perror strerror C review example
#include <stdio.h>
int main(void) {
    printf("C Error Handling errno perror strerror: normal path\n");
    return 0;
}

C Error Handling errno perror strerror C boundary example

C Error Handling errno perror strerror C boundary example
#include <stdio.h>
int main(void) {
    int count = 0;
    if (count == 0) printf("C Error Handling errno perror strerror: empty input\n");
    return 0;
}
Key Takeaways
  • Explain the purpose of C Error Handling errno, perror, strerror before memorizing syntax.
  • Run or trace one small C Language example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for C Error Handling errno, perror, strerror.
  • Write the rule in your own words after checking the example.
  • Connect C Error Handling errno, perror, strerror to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing C Error Handling errno perror strerror without the situation where it is useful.
RIGHT Connect C Error Handling errno perror strerror to a concrete C Language task.
Purpose makes syntax easier to recall.
WRONG Testing C Error Handling errno perror strerror only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to C Error Handling errno perror strerror.
Evidence keeps debugging focused.
WRONG Memorizing C Error Handling errno perror strerror without the situation where it is useful.
RIGHT Connect C Error Handling errno perror strerror to a concrete C Language task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to C Error Handling errno, perror, strerror, then fix it and explain the fix.
  • Summarize when to use C Error Handling errno, perror, strerror and when another approach is better.
  • Write a small example that uses C Error Handling errno perror strerror in a realistic C Language scenario.
  • Change one important value in the C Error Handling errno perror strerror example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in C Language, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.