Skip to main content
Advertisement

C: Error Handling and Safety

Since C does not have exception handling syntax (like try-catch) found in higher-level languages, errors must be handled using function return values or status variables.

1. Error Checking via Return Values

Many standard C functions return 0 or a positive value on success, and -1 or NULL on failure.

#include <stdio.h>

int main() {
FILE *fp = fopen("nonexistent.txt", "r");

if (fp == NULL) {
printf("Error: Could not open the file.\n");
return 1; // Signal abnormal termination
}

fclose(fp);
return 0;
}

2. Utilizing the exit() Function

Used to terminate the program immediately when a fatal error occurs.

#include <stdlib.h>

if (error_condition) {
exit(EXIT_FAILURE); // Force terminate the program
}

warning

In C, neglecting error handling can lead to runtime crashes such as "Segmentation Faults." Therefore, consistently checking return values is critical.

Advertisement