Error Handling Material
Error Handling Material
1. Return Codes
Example:
#include <stdio.h>
int main() {
int result = divide(10, 0);
if (result == -1) {
printf("Error: Division by zero!\n");
} else {
printf("Result: %d\n", result);
}
return 0;
}
Overview: The global variable errno holds error codes set by system calls and
library functions (like malloc(), open(), etc.). perror() can be used to print the
corresponding error message based on errno.
Example:
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
perror("Error opening file");
} else {
fclose(file);
}
return 0;
}
Example
#include <stdio.h>
#include <setjmp.h>
jmp_buf buf;
void myFunction() {
printf("Inside function\n");
longjmp(buf, 1); // Jump back to setjmp
printf("This will not be printed.\n");
}
int main() {
if (setjmp(buf) != 0) {
printf("Error: An error occurred!\n");
} else {
myFunction(); // Call a function that causes an error
}
return 0;
}
Inside function
Error: An error occurred!
Note: longjmp() causes the program to jump back to the point of setjmp() and
can be used for error recovery.
4. assert() for Debugging
Overview: The assert() macro from the assert.h header checks whether an
expression is true. If it's false, the program prints an error message and abort
Example
#include <stdio.h>
#include <assert.h>
int main() {
int result = divide(10, 0); // This will trigger an assertion failure
printf("Result: %d\n", result);
return 0;
}
Many library functions return error codes. For example, the malloc() function
returns NULL when memory allocation fails. Checking for NULL after using
malloc() is important.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(10 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Use arr
free(arr);
return 0;
}
You can define your own error handling mechanism. For example, creating a
function that logs errors to a file.
Example:
#include <stdio.h>
int main() {
log_error("File not found.");
return 0;
}
When an error occurs that prevents the program from continuing, you can use
exit() to terminate the program. You can pass a status code to indicate success
or failure (0 for success, non-zero for failure).
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Fatal error occurred, exiting...\n");
exit(1); // Exit the program with an error code
}