Error Handling in C
⏱ Estimated reading time: 2 min
Error handling in C is the process of detecting, reporting, and handling errors that occur during program execution.
C does not have built-in exception handling, so errors are handled using return values, error codes, and library functions.
Types of Errors in C
-
Compile-time Errors
-
Run-time Errors
-
Logical Errors
1. Compile-time Errors
Errors detected by the compiler.
Examples:
-
Syntax errors
-
Missing semicolons
-
Undeclared variables
2. Run-time Errors
Errors that occur during program execution.
Examples:
-
Division by zero
-
File not found
-
Invalid memory access
3. Logical Errors
Errors in program logic.
Examples:
-
Wrong formula
-
Incorrect condition
Error Handling Using return Values
Functions return special values to indicate errors.
Using errno Variable
-
errnois a global variable set when an error occurs -
Requires
errno.h
perror() Function
Prints a descriptive error message.
strerror() Function
Returns error message as a string.
Example Program
Handling File Errors
-
Check file pointer for
NULL -
Use
perror()for error description
Handling Memory Allocation Errors
Summary
-
C uses manual error handling
-
Errors are checked using return values
-
errno,perror(), andstrerror()help identify errors -
Proper checks prevent program crashes
Register Now
Share this Post
← Back to Tutorials