⚠
Error Handling in C
🏠 Home Lecture 24: Errors
The Problem ⚡

What happens when things go wrong?

Unlike Java or Python, C does NOT have try-catch blocks. If you divide by zero or open a missing file, your program just crashes. We must handle errors manually!

⚠️ The Crash Scenario

Which of these is the developer's responsibility in C?
Checking for Divide by Zero
Checking Array Bounds
Checking if File Exists
crash.cDangerous Code 💀
// 1. Divide by Zero (Arithmetic Exception) int a = 10 / 0; // CRASH! 💥 // 2. Array Out of Bounds (Segmentation Fault) int arr[5]; arr[1000] = 50; // CRASH! 💥 // 3. Null Pointer Dereference (Segmentation Fault) FILE *ptr = fopen("missing.txt", "r"); fgetc(ptr); // CRASH! 💥
Logic Checks

Handling Logical & Memory Errors

To prevent math errors and array bounds violations, we use simple if conditions to sanitize inputs before using them.

logic_safe.cHover to explore ✶
// --- Safe Division --- int num = 10, den = 0; if (den == 0) { printf("Error: Division by zero is not allowed!\n"); } else { printf("Result: %d\n", num / den); } // --- Safe Array Access --- int arr[5] = {1, 2, 3, 4, 5}; int index = 10; if (index < 0 || index >= 5) { printf("Error: Array index out of bounds!\n"); } else { printf("Value: %d\n", arr[index]); }
🛡️ Defensive Programming

Don't trust user input. If a user provides an index or a denominator, always check it against the limits of your data structure before executing the logic.
File System Checks

Checking for File Existence

Similarly, to prevent file-related crashes, we must ALWAYS check if the file pointer is NULL immediately after calling fopen().

file_safe.cHover to explore ✶
FILE *ptr = fopen("data.txt", "r"); if (ptr == NULL) { printf("Error: File does not exist!\n"); return 1; // Stop the program safely } // Safe to read now! char ch = fgetc(ptr); fclose(ptr);
💾 The Golden Rule of Files:

Open → Check for NULL → Process → Close
Why does fopen fail?
1. File not found ("r" mode)
2. Permission Denied
3. Hard Disk is Full
Advanced C

Robust Error Tools (perror & exit)

Instead of a simple printf, professional C programs use standard library tools like perror() and exit() to handle errors gracefully and provide exact system reasons.

robust_code.cProfessional Way
#include <stdio.h> #include <stdlib.h> // Needed for exit() #include <errno.h> // Error number tracking void openSystemFile() { FILE *ptr = fopen("C:\\Windows\\secret.txt", "r"); if (ptr == NULL) { perror("File Error"); exit(EXIT_FAILURE); } fclose(ptr); }

Terminal Output (No rights)

File Error: Permission Denied
What is errno?
When a system call fails, C sets a global integer variable called errno. perror() looks at this number and prints the human-readable string associated with it!
Knowledge Check ✍

Let's test what you've learned!

Question 1 of 3
Loading...