C Error Handling

C Tutorial

⚠️ C Error Handling

Unlike some modern languages, C does not have built-in exception handling (like try-catch).
Instead, C uses several alternative mechanisms for detecting and managing errors manually.


🔹 Methods of Error Handling in C

MethodUsed For
Return valuesFunction failure signals
errnoGlobal error reporting
perror() / strerror()Human-readable error messages
Assertions (assert)Debugging and sanity checks
setjmp() / longjmp()Manual exception-like behavior


 1. Error Handling using Return Values

Functions often return special values like -1, NULL, or 0 to indicate failure.

Example:


 


 2. Error Handling Using errno

errno is a global variable set by some library functions when an error occurs.

Include:

#include <errno.h>
#include <string.h>
#include <stdio.h>

Example:


 


 3. perror() and strerror()

FunctionPurpose
perror("message")Prints a system error message with context
strerror(errno)Returns error message as a string

Example:


 

Output example:

File open failed: No such file or directory

4. Using assert() (Debugging Only)

Stops the program if a condition is false.


 

⚠️ Assertions are removed in production builds using:

gcc -DNDEBUG program.c

 5. setjmp() and longjmp() (Manual Exception Handling)

Used to jump to a saved execution point — similar to exceptions.


 


🧪 Real Example: Safe File Opening


 


🧠 Best Practices

✔ Always check return values (especially for I/O and pointer operations)
✔ Use errno, perror(), and strerror() for readable errors
✔ Use assert() in debugging, not production
✔ Use setjmp() and longjmp() only for advanced cases


🏁 Summary Table

TechniqueBest For
Return codesSimple functions
errnoSystem/library errors
perror() / strerror()User-friendly error messages
assert()Debug/testing
setjmp() / longjmp()Advanced error control

You may also like...