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.
return
valueserrno
perror()
and strerror()
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
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; }
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"); }
#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; }
malloc()
, fopen()
, etc.).perror()
or strerror(errno)
for meaningful messages.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!