๐Ÿง  C Advanced Topics
Estimated reading: 3 minutes 7 views

โ— C Error Handling โ€“ Using errno, perror, and strerror Effectively


๐Ÿงฒ Introduction โ€“ How Is Error Handling Done in C?

C programming uses a minimal but flexible error-handling model based on global variables and diagnostic functions. Since C lacks exceptions (like in C++ or Java), errors from standard library functions must be manually checked, interpreted, and reported using tools like errno, perror(), and strerror().

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to detect and interpret runtime errors
  • The role of errno, perror(), and strerror()
  • Real-world use cases and practical examples
  • Best practices for robust and clear error reporting

๐Ÿ” What Is errno in C?

errno is a global integer variable defined in <errno.h> that gets set by many standard library functions when an error occurs. It holds an error code that you can convert into a human-readable string using strerror() or display using perror().

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

๐Ÿง  Always check the functionโ€™s return value before accessing errno.


๐Ÿ’ก Common Functions That Set errno

FunctionFails When…
fopen()File doesnโ€™t exist or cannot be opened
malloc()No memory available
strtol()Input not convertible to a number
read()/write()I/O failure

๐Ÿ–จ๏ธ perror() โ€“ Print Descriptive Error Message

perror("message") prints the custom message, followed by a colon and system error description based on errno.

โœ… Example:

FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
    perror("Error opening file");
}

๐Ÿ–จ๏ธ Output:

Error opening file: No such file or directory

๐Ÿงพ strerror() โ€“ Get Error Message String

strerror(errno) returns a string corresponding to the current error code.

printf("Error: %s\n", strerror(errno));

This method is useful when you want custom formatting or logging.


๐Ÿ’ป Complete Example

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

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

๐Ÿ“š Real-World Use Cases

ScenarioFunction UsedError Description
File not foundfopen()ENOENT (No such file)
Disk fullfwrite()ENOSPC (No space left)
Permission deniedopen()EACCES (Access denied)
Invalid input formatstrtol()EINVAL (Invalid arg)

๐Ÿ’ก Best Practices & Tips

๐Ÿ“˜ Best Practice:
Always check a functionโ€™s return value before checking errno, as errno may hold a stale error code.

๐Ÿ’ก Tip:
Use errno, perror(), and strerror() in combination for flexible and developer-friendly error output.

โš ๏ธ Pitfall:
Never assume errno == 0 means successโ€”many functions only set errno on failure, and not all failures update it.


๐Ÿ“Œ Summary โ€“ Recap & Next Steps

C’s error handling model is simple but powerful when used properly. By using errno in tandem with perror() and strerror(), you can detect, diagnose, and report errors gracefully.

๐Ÿ” Key Takeaways:

  • Use errno to capture error codes from failed functions
  • Use perror() to print a system-generated message with context
  • Use strerror(errno) to retrieve error message strings for logging
  • Always validate the return value before checking errno

โš™๏ธ Real-World Relevance:

Crucial in file I/O, memory allocation, system calls, and robust C applications requiring detailed failure reporting.


โ“ Frequently Asked Questions (FAQ)

โ“ What is errno used for?

โœ… It holds the error code when a library/system call fails, helping identify what went wrong.


โ“ What does perror() do?

โœ… It prints a message followed by the textual representation of errno.


โ“ Should I reset errno before a function call?

โœ… Itโ€™s not required but good practice in some cases to avoid checking a stale value.


โ“ What is the difference between perror() and strerror()?

โœ… perror() prints to stderr automatically.
strerror() returns a message string that you can format and log manually.


โ“ Where is errno defined?

โœ… In the <errno.h> header.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

โ— C Error Handling (errno, perror)

Or Copy Link

CONTENTS
Scroll to Top