Skip to main content
C Programming Basics
CHAPTER 27 Beginner

Error Handling in C

Updated: May 17, 2026
5 min read

# CHAPTER 27

Error Handling in C

1. Introduction

Unlike Java or Python, C does not have try-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 errno global variable.
  • Use perror() and strerror() to print readable error messages.
  • Understand the difference between stdout and stderr.

3. Return Values (The First Line of Defense)

Most standard C functions return specific values to indicate failure.
  • fopen() returns NULL if it fails.
  • malloc() returns NULL if it fails.
  • Mathematical functions might return -1 or NaN.

Always check return values!

c
12345
FILE *file = fopen("missing.txt", "r");
if (file == NULL) {
    printf("Failed to open file.\n");
    // Handle error (exit or ask for new file)
}

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>.

c
12345678910111213
#include <stdio.h>
#include <errno.h>
#include <math.h>

int main() {
    FILE *file = fopen("missing.txt", "r");
    
    if (file == NULL) {
        printf("Error number: %d\n", errno); 
        // Example output: Error number: 2 (which means "No such file or directory")
    }
    return 0;
}

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.
c
1234567891011
#include <stdio.h>

int main() {
    FILE *file = fopen("missing.txt", "r");
    
    if (file == NULL) {
        // Prints: "File error: No such file or directory"
        perror("File error"); 
    }
    return 0;
}

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>.
c
12345678910111213
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    FILE *file = fopen("missing.txt", "r");
    
    if (file == NULL) {
        // Logs the exact error string
        fprintf(stderr, "Log: %s\n", strerror(errno));
    }
    return 0;
}

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!

c
12345
// Normal text goes to stdout
printf("Processing data...\n"); 

// Errors MUST go to stderr!
fprintf(stderr, "ERROR: Memory allocation failed!\n");

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.
c
123
int a = 5, b = 0;
// if (b == 0) { handle it! }
// int c = a / b; // CRASH! Floating point exception

Fix: Always validate user input *before* doing math!

9. Common Mistakes

  • Assuming errno is 0: errno is only updated when a function *fails*. If a function succeeds, it does NOT reset errno to 0. It retains the last error code.
  • Using printf for errors: Always use fprintf(stderr, ...) or perror() so errors aren't hidden if output is redirected.

10. Exercises

  1. 1. Write a program that asks the user for a filename, tries to open it, and uses perror() if it fails.
  1. 2. Write a function safeDivide(int a, int b) that checks if b is 0 and prints to stderr if it is, returning a default value.

11. MCQ Quiz with Answers

Q1. Does C have try-catch blocks? a) Yes b) No Answer: b) No
Question 2

What is errno?

Question 3

Which header file is required to use errno?

Question 4

What does perror("Error") do?

Question 5

Which function returns the error string without printing it?

Question 6

Where should error messages be printed?

Question 7

Why use stderr instead of stdout?

Question 8

What happens if a C program divides by zero?

Q9. Is errno automatically reset to 0 upon a successful function call? a) Yes b) No Answer: b) No
Question 10

If malloc fails, what does it return?

12. Interview Questions

  • Q: Explain the difference between perror() and strerror().
  • Q: Why do we separate stdout and stderr streams 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 (like NULL), 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 like memcpy and memset.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·