Error Handling in C
# CHAPTER 27
Error Handling in C
1. Introduction
Unlike Java or Python, C does not havetry-catch blocks for Exception Handling. In C, you are entirely responsible for checking if a function succeeded or failed. Robust C programs check the return value of *every* system call and handle errors gracefully rather than crashing.
2. Learning Objectives
By the end of this chapter, you will be able to:- Understand how C functions report errors.
-
Use the
errnoglobal variable.
-
Use
perror()andstrerror()to print readable error messages.
-
Understand the difference between
stdoutandstderr.
3. Return Values (The First Line of Defense)
Most standard C functions return specific values to indicate failure.-
fopen()returnsNULLif it fails.
-
malloc()returnsNULLif it fails.
-
Mathematical functions might return
-1orNaN.
Always check return values!
4. The errno Variable
When a system call fails, it doesn't just return NULL or -1; it also sets a global integer variable called errno (Error Number). This variable indicates *exactly* what went wrong.
You must #include <errno.h>.
5. Making Errors Readable: perror()
Printing "Error number 2" is not helpful to a user. The perror() function automatically translates errno into a human-readable string and prints it to the screen.
6. Using strerror()
If you don't want to print the error immediately (e.g., you want to log it to a file), use strerror(). It returns the error string as a char*. You must #include <string.h>.
7. Understanding stderr
In C, there are three standard data streams:
-
stdin(Standard Input - Keyboard)
-
stdout(Standard Output - Screen)
-
stderr(Standard Error - Screen)
Why have both stdout and stderr if they both print to the screen? Because in the terminal, users can redirect output to a file (./app > output.txt). By default, this only redirects stdout. Error messages printed to stderr will still show up on the screen, ensuring the user sees the crash!
8. Divide by Zero (A Hardware Exception)
Some errors, like dividing by zero, are Hardware Exceptions. The CPU detects it and sends a signal (SIGFPE) to the OS, which instantly kills the program.errno cannot catch this.
Fix: Always validate user input *before* doing math!
9. Common Mistakes
-
Assuming
errnois 0:errnois only updated when a function *fails*. If a function succeeds, it does NOT reseterrnoto 0. It retains the last error code.
-
Using
printffor errors: Always usefprintf(stderr, ...)orperror()so errors aren't hidden if output is redirected.
10. Exercises
-
1.
Write a program that asks the user for a filename, tries to open it, and uses
perror()if it fails.
-
2.
Write a function
safeDivide(int a, int b)that checks ifbis 0 and prints tostderrif it is, returning a default value.
11. MCQ Quiz with Answers
Q1. Does C havetry-catch blocks?
a) Yes b) No
Answer: b) No
What is errno?
Which header file is required to use errno?
What does perror("Error") do?
Which function returns the error string without printing it?
Where should error messages be printed?
Why use stderr instead of stdout?
What happens if a C program divides by zero?
errno automatically reset to 0 upon a successful function call?
a) Yes b) No
Answer: b) No
If malloc fails, what does it return?
12. Interview Questions
-
Q: Explain the difference between
perror()andstrerror().
-
Q: Why do we separate
stdoutandstderrstreams in POSIX systems?
- Q: How do you handle errors in C since there is no Exception Handling? (Answer: Check return codes and errno immediately).
13. Summary
Error handling in C is a manual process. You must check function return values (likeNULL), inspect the global errno variable for the specific error code, and use perror() or fprintf(stderr, ...) to communicate the failure to the user safely.
14. Next Chapter Recommendation
In Chapter 28: Typecasting and Memory Manipulation, we will look at how to forcibly convert data types and use fast memory operations likememcpy and memset.