Error Handling in C

📘 C 👁 28 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Error handling in C is the process of detecting, reporting, and handling errors that occur during program execution.
C does not have built-in exception handling, so errors are handled using return values, error codes, and library functions.


Types of Errors in C

  1. Compile-time Errors

  2. Run-time Errors

  3. Logical Errors


1. Compile-time Errors

Errors detected by the compiler.

Examples:

  • Syntax errors

  • Missing semicolons

  • Undeclared variables


2. Run-time Errors

Errors that occur during program execution.

Examples:

  • Division by zero

  • File not found

  • Invalid memory access


3. Logical Errors

Errors in program logic.

Examples:

  • Wrong formula

  • Incorrect condition


Error Handling Using return Values

Functions return special values to indicate errors.

if (fp == NULL) { printf("File cannot be opened"); }

Using errno Variable

  • errno is a global variable set when an error occurs

  • Requires errno.h

#include

perror() Function

Prints a descriptive error message.

perror("Error");

strerror() Function

Returns error message as a string.

strerror(errno);

Example Program

#include #include #include int main() { FILE *fp; fp = fopen("data.txt", "r"); if (fp == NULL) { perror("File Error"); return 1; } fclose(fp); return 0; }

Handling File Errors

  • Check file pointer for NULL

  • Use perror() for error description


Handling Memory Allocation Errors

int *p = malloc(10 * sizeof(int)); if (p == NULL) { printf("Memory allocation failed"); }

Summary

  • C uses manual error handling

  • Errors are checked using return values

  • errno, perror(), and strerror() help identify errors

  • Proper checks prevent program crashes


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes