Introduction
Error handling helps your program deal with problems without crashing. It makes your program safer and easier to fix.
Error handling helps your program deal with problems without crashing. It makes your program safer and easier to fix.
In C, error handling is often done by checking return values or using errno. Example: if (function_call() == ERROR) { // handle error }
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "r"); if (file == NULL) { printf("Error: Could not open file.\n"); return 1; } // use file fclose(file); return 0; }
#include <stdio.h> int divide(int a, int b) { if (b == 0) { printf("Error: Division by zero.\n"); return 0; // or some error code } return a / b; }
This program tries to open a file that does not exist. It shows how error handling stops the program from crashing and informs the user.
#include <stdio.h> int main() { FILE *file = fopen("missing.txt", "r"); if (file == NULL) { printf("Error: File not found.\n"); return 1; } printf("File opened successfully.\n"); fclose(file); return 0; }
Always check for errors after operations like file access or memory allocation.
Ignoring errors can cause your program to behave unpredictably or crash.
Error handling keeps programs safe and stable.
In C, you check errors by looking at return values.
Always handle possible errors to improve your program.
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
} else {
printf("File opened successfully\n");
fclose(file);
}FILE *f = fopen("input.txt", "r");
char buffer[100];
fgets(buffer, 100, f);
printf("%s", buffer);
fclose(f);Pass the test and this pattern moves unknown