🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C Notes
Topic #90

C Error Handling


Error Handling in C

Error handling lets you detect and respond to problems in your program, like a file that can't be opened or memory that can't be allocated, so your program doesn't crash or behave unexpectedly.

Unlike some languages, C does not have built-in exception handling (like try/catch). Instead, C uses return values, global error codes, and helper functions like perror() and strerror().


Using Return Values

In the previous chapter, you learned that functions like fopen() return NULL when something goes wrong.

You can check for NULL using an if statement to detect and handle errors before your program crashes.

In the example below, we try to open a file that does not exist. Since fopen() fails, it returns NULL and we print an error message:

Example: fopen() fails

#include <stdio.h>

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

  if (fptr == NULL) {
    printf("Error opening file.\\n");
    return 1;
  }

  fclose(fptr);
  return 0;
}

Get More Details

If you want more details about what went wrong, you can use the perror() function.

It prints a custom error message followed by a description of the last error that occurred:

Example: perror() with fopen()

#include <stdio.h>

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    perror("Error opening file");
    return 1;
  }

  fclose(f);
  return 0;
}

Using strerror() and errno

errno is a global variable that stores the error code from the last failed operation. You can include <errno.h> to access it, and strerror(errno) will convert the error code into a readable message:

Example: strerror()

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

int main() {
  FILE *f = fopen("nothing.txt", "r");

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

  fclose(f);
  return 0;
}

Common Error Codes

Error constants are defined in <errno.h>. You can compare errno to them to detect specific issues:

Error Code Meaning
ENOENT No such file or directory
EACCES Permission denied
ENOMEM Not enough memory
EINVAL Invalid argument

Example: Custom message for ENOENT

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

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    if (errno == ENOENT) {
      printf("The file was not found.\n");
    } else {
      printf("Some other file error occurred.\n");
    }
    return 1;
  }

  fclose(f);
  return 0;
}

Using exit() to Stop the Program

If you want to stop the program immediately when an error occurs, you can use exit(). It lets you return a status code to the operating system.

Exit codes help signal whether the program finished successfully or with an error, like:

  • 0 means success
  • Non-zero values (like 1 or EXIT_FAILURE) indicate errors

Example: Using exit() on error

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

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    printf("Failed to open file.\n");
    exit(1);
  }

  fclose(f);
  return 0;
}

Common Exit Status Codes

Code Meaning
0 Success - the program completed normally
1 Error - something went wrong
EXIT_SUCCESS Same as 0 (defined in <stdlib.h>)
EXIT_FAILURE Same as a non-zero error code (also in <stdlib.h>)

Tip: You can use EXIT_SUCCESS and EXIT_FAILURE instead of numbers to make your code more readable.

Example: Using EXIT_FAILURE and EXIT_SUCCESS

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

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    perror("Could not open nothing.txt");
    exit(EXIT_FAILURE); // More readable than exit(1)
  }

  fclose(f);
  return EXIT_SUCCESS;
}

Summary

  • Many C functions return NULL when something goes wrong
  • Use perror() to print a message about the error
  • Use strerror(errno) to get the error message as a string
  • errno stores the error code from the last failed action
  • You can compare errno to values like ENOENT (file not found) or ENOMEM (not enough memory)
  • Use exit() to stop the program early if there's an error

Tip: Always check for errors after file operations, memory allocation, and system calls. Ignoring errors can lead to unexpected behavior or crashes.

Want to go beyond the notes?

Join CodingNow 2.0's C course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

C Error Handling – FAQs

Quick answers about learning C Error Handling in C.

This free note from CodingNow 2.0 explains C Error Handling in C — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C topic on CodingNow 2.0, including C Error Handling, is 100% free with no signup required.
With focused practice, most students grasp C Error Handling in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now