Unlike modern languages like Java or Python, C does not have built-in "Exceptions" (try/catch). In C, Error Handling is done manually by checking return values of functions and using specific system variables to identify what went wrong.
Most C functions return a specific value to indicate an error. Usually, a function returns -1 or NULL if it fails, and 0 or a valid pointer if it succeeds.
main() return 0 for success and non-zero for failure.fopen() or malloc() return NULL on failure.When a system call fails, it sets a global variable called errno. This is an integer representing the specific error code. To use it, you must include the <errno.h> header.
Since error numbers (like 2 or 12) are hard to understand, C provides two functions to convert errno into human-readable text:
| Function | Description |
|---|---|
perror("msg") |
Prints your custom message followed by the system error description. |
strerror(errno) |
Returns a pointer to the textual string representation of the current errno. |
While there are many error codes, these are the ones you will encounter most frequently:
sqrt()).To make your code more readable, you can use macros from <stdlib.h> when terminating your program.
if (b != 0) { c = a / b; }.stderr instead of stdout for printing error messages. This ensures errors are visible even if the user redirects the standard output to a file! fprintf(stderr, "Error occurred!\n");