C Tutorial



ERROR HANDLING IN C


⚠️ Error Handling in C

Error handling is crucial in C programming to make your code more stable and user-friendly. It helps you catch and manage unexpected situations like file failures, memory issues, or invalid user inputs.

🧠 Why Error Handling?
Because real-world programs never go 100% perfect — error handling saves your program from crashing and provides meaningful messages to the user.

🛠️ Common Methods for Error Handling

  • Using return values
  • Using errno
  • Using perror() and strerror()

✅ Return Values for Error Detection

Most standard functions in C return special values to indicate an error.

FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
    printf("Error: File not found!\n");
}
  

🔢 errno - Global Error Code

errno is a global variable that gets automatically set when a library function fails.

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

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

🗣️ perror() - Print Standard Error

The perror() function prints a description of the last error that occurred.

FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
    perror("Unable to open file");
}
  

🔍 strerror() - Get Error as Text

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

int main() {
    FILE *fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("Error: %s\n", strerror(errno));
    }
    return 0;
}
  
💡 Tips:
  • Always check the return values of critical functions (like malloc(), fopen(), etc.).
  • Use perror() or strerror(errno) for meaningful messages.
  • Never assume everything will work — always code for failure!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review