Error Handling in C (errno, perror, strerror)

C does not have built-in exception handling like modern languages. Instead, C provides a lightweight mechanism for detecting runtime errors using: errno, perror(), and strerror() These functions and global variables help identify what went wrong during program execution.

What Causes Runtime Errors?

errno – Global Error Indicator

errno is a global integer variable defined in <errno.h>. It stores the error code of the last failed operation.

perror() – Prints Error Message

perror() prints a human-readable error message based on the current value of errno.

strerror() – Returns Error Message String

strerror(errno) returns the error message as a string so you can print it manually.

Common Error Codes (errno)

Examples – All in One Block

1. Using errno and perror()

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

int main() {

    FILE *f = fopen("no_file.txt", "r");

    if(f == NULL){
        perror("Error Opening File");
    }

    return 0;
}

2. Using strerror() with errno

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

int main() {

    FILE *f = fopen("no.txt", "r");

    if(!f){
        printf("Failed: %s", strerror(errno));
    }

    return 0;
}

3. malloc() Failure Detection

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

int main() {

    int *p = malloc(100000000000L);

    if(!p){
        printf("Memory Error: %s", strerror(errno));
    }

    return 0;
}

4. fopen() Permission Error

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

int main() {

    FILE *fp = fopen("/root/system.txt", "r");

    if(!fp){
        perror("Access Denied");
    }

    return 0;
}

5. Custom Error Logging

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

int main() {

    FILE *f = fopen("unknown.bin", "rb");

    if(f == NULL){
        printf("Error Code: %d\n", errno);
        printf("Message: %s", strerror(errno));
    }

    return 0;
}

When Should You Use These?

Practice Questions

  1. What is errno? When does it change?
  2. Difference between perror() and strerror()
  3. Write a program to detect file opening failure.
  4. Explain three common errno values.
  5. Why does C not have exception handling like C++?

Practice Task

Write a C program that:
✔ Tries to open a file ✔ Displays error using perror() ✔ Displays error using strerror() ✔ Prints the errno code