Error Handling in C
Definition
Error Handling in C is the process of detecting, reporting, and handling errors that occur during program execution so that the program does not terminate unexpectedly.
Unlike some programming languages, C does not provide built-in exception handling (such as try, catch, or throw). Instead, errors are handled using return values, error codes, the errno variable, and standard library functions.
Types of Errors in C
There are mainly three types of errors in C.
1. Compile-Time Errors
Definition
Compile-time errors are errors that occur when the compiler translates the source code into machine code. These errors must be fixed before the program can be executed.
Example
#include<stdio.h>
int main()
{
printf("Hello World")
return 0;
}
Error
Error: expected ';' before 'return'
Common Causes
- Missing semicolon (
;) - Undeclared variables
- Missing header files
- Syntax errors
2. Run-Time Errors
Definition
Run-time errors occur while the program is executing. These errors may cause the program to crash or produce unexpected behavior.
Example
#include<stdio.h>
int main()
{
int a = 10;
int b = 0;
printf("%d", a / b);
return 0;
}
Output
Runtime Error
Division by zero
Common Causes
- Division by zero
- Invalid memory access
- File not found
- Null pointer dereference
3. Logical Errors
Definition
Logical errors occur when the program compiles and runs successfully but produces incorrect output due to incorrect program logic.
Example
#include<stdio.h>
int main()
{
int a = 10, b = 20;
printf("%d", a - b);
return 0;
}
Output
-10
If the programmer intended to add the numbers, the correct output should have been:
30
Error Handling Techniques in C
1. Using Return Values
Many C library functions return a value indicating success or failure.
Example
#include<stdio.h>
int divide(int a, int b)
{
if(b == 0)
{
return -1;
}
return a / b;
}
int main()
{
int result = divide(20, 5);
if(result == -1)
printf("Error: Division by zero");
else
printf("Result = %d", result);
return 0;
}
Output
Result = 4
2. Using errno
Definition
errno is a global variable declared in the <errno.h> header file. It stores an error code when a library function fails.
Example
#include<stdio.h>
#include<errno.h>
int main()
{
FILE *fp;
fp = fopen("data.txt", "r");
if(fp == NULL)
{
printf("Error Number = %d\n", errno);
}
return 0;
}
Possible Output
Error Number = 2
3. Using perror()
Definition
The perror() function prints a user-defined message followed by a description of the last system error.
Syntax
perror("Message");
Example
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("abc.txt", "r");
if(fp == NULL)
{
perror("File Error");
}
return 0;
}
Output
File Error: No such file or directory
4. Using strerror()
Definition
The strerror() function converts an error number (errno) into a readable error message.
Example
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE *fp;
fp = fopen("abc.txt", "r");
if(fp == NULL)
{
printf("%s\n", strerror(errno));
}
return 0;
}
Output
No such file or directory
File Error Handling Example
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("student.txt", "r");
if(fp == NULL)
{
printf("File cannot be opened.\n");
return 1;
}
printf("File opened successfully.\n");
fclose(fp);
return 0;
}
Output (if file exists)
File opened successfully.
Output (if file does not exist)
File cannot be opened.
Memory Allocation Error Handling
When using malloc(), always check whether memory allocation was successful.
Example
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;
ptr = (int *)malloc(sizeof(int));
if(ptr == NULL)
{
printf("Memory allocation failed.");
return 1;
}
*ptr = 100;
printf("%d", *ptr);
free(ptr);
return 0;
}
Output
100
Advantages of Error Handling
- Prevents unexpected program crashes.
- Helps identify and debug errors.
- Makes programs more reliable and robust.
- Improves user experience by displaying meaningful error messages.
- Allows the program to recover gracefully from certain errors.
Disadvantages of Error Handling
- Increases program complexity.
- Requires additional code.
- Improper error handling can still lead to bugs or resource leaks.
- Excessive checking may slightly affect performance.
Summary
- Error Handling is the process of detecting and managing errors during program execution.
- C does not support exception handling (
try/catch); it uses return values,errno,perror(), andstrerror()instead. - The three main types of errors are:
- Compile-Time Errors โ syntax and compilation mistakes.
- Run-Time Errors โ errors that occur while the program is running.
- Logical Errors โ mistakes in program logic that produce incorrect results.
- Always check the return values of functions such as
fopen(),malloc(), and other library functions to write safe and reliable C programs.
