Error Handling: Dealing with the Unexpected
7 min read
10. Error Handling: Dealing with the Unexpected
Welcome to the messy reality of programming! 🏗️ Up until now, we’ve lived in a utopia where users always enter the correct numbers, files always exist, and the internet connection never drops.
In the real world, things break. Hard drives fill up, servers time out, and users try to divide by zero just to see what happens.
This guide covers how C++ handles these "oops" moments. We will move from the old-school methods to the modern C++ standard of Exception Handling.
1. The Philosophy of Exceptions vs. Error Codes
Before writing code, we must understand the strategy. How do we communicate that a function failed?
The Problem: The "Ignored" Return Value
In older C-style programming, functions often returned "Error Codes" to signal failure.
- Definition: An Error Code is a specific return value (usually an integer like
-1or0) designated to indicate that a function did not complete successfully.
Scenario: Imagine you have a function readFile().
- If it works, it returns
1. - If the file is missing, it returns
-1.
The problem? You, the programmer, can simply ignore that return value. You can call readFile() and assume it worked, leading to a crash later when you try to use empty data. It's like a fire alarm that just sends you a polite email that you never read. 🔥
The Solution: Exceptions
C++ introduced Exceptions.
- Definition: An Exception is an object created to signal an anomalous condition. When thrown, it forces the program to stop its normal execution path and jump to a specialized error-handling block.
If you ignore an exception, your program doesn't just proceed with bad data—it crashes immediately and loudly (calls std::terminate). This forces developers to acknowledge errors.
Industry Perspective 🏭
- Error Codes: Still used in systems programming, embedded devices (where memory is tight), or when failure is expected (e.g., "User input invalid").
- Exceptions: The standard for general C++ application logic. Used when a failure is truly exceptional (e.g., "Database connection severed").
Fun Fact: Google's internal C++ Style Guide actually forbids C++ exceptions for legacy reasons! However, the rest of the C++ world (ISO Standards) embraces them. knowing how to use them is mandatory for a C++ developer.
2. Throwing Exceptions: Sounding the Alarm
How do we actually trigger this alarm? We use the throw keyword.
- Definition: The
throwkeyword transfers control of the program from the current location to the nearest compatible exception handler in the call stack.
The Concept: Stack Unwinding
When you throw, C++ stops the current function. It looks for a handler. If it doesn't find one, it kills the function, pops it off the stack, and checks the function that called it. This process repeats until a handler is found or the program terminates.
Crucially, during this "Stack Unwinding," C++ calls the destructors of all local objects. This ensures memory is cleaned up (this is a vital part of RAII - Resource Acquisition Is Initialization).
Code Example
Let's build a function that divides numbers but refuses to divide by zero.
double distinctDivision(double numerator, double denominator) {
if (denominator == 0) {
// We found a problem. Stop everything.
// We are throwing a primitive integer here (simple, but rarely used in pros).
throw 404;
}
return numerator / denominator;
}
int main() {
// If we run this, the program will abort because we threw,
// but nobody caught the ball!
distinctDivision(10, 0);
return 0;
}What happens under the hood:
denominatoris 0.throw 404is executed.- The function
distinctDivisionstops immediately. - Control shoots up to
main. maindoesn't handle it.- Operating System kills the program.
3. Catching Exceptions: try and catch Blocks
A thrown exception is a hot potato. 🥔 You need someone to catch it, or it burns the house down.
- Definition:
- A
tryblock identifies a region of code where exceptions might occur. - A
catchblock follows atryblock and contains the code to handle the exception.
- A
The Syntax
You wrap dangerous code in try. You write recovery code in catch.
Practical Example
#include <iostream>
double distinctDivision(double numerator, double denominator) {
if (denominator == 0) {
throw "Division by Zero Error!"; // Throwing a string literal
}
return numerator / denominator;
}
int main() {
double a = 10;
double b = 0;
try {
// 1. We enter the dangerous zone
std::cout << "Attempting division..." << std::endl;
// 2. This function throws. Execution inside 'try' stops immediately after this line.
double result = distinctDivision(a, b);
// 3. This line is SKIPPED entirely
std::cout << "Result is: " << result << std::endl;
}
catch (const char* errorMessage) {
// 4. We catch the specific type thrown (const char*)
std::cerr << "Oh no! Something went wrong: " << errorMessage << std::endl;
// 5. The program continues normally after the catch block.
}
std::cout << "Program finished gracefully." << std::endl;
return 0;
}Output:
Attempting division...
Oh no! Something went wrong: Division by Zero Error!
Program finished gracefully.The "Catch All" Handler
Sometimes you don't know what might be thrown. You can use the ellipsis ... syntax.
try {
// risky code
} catch (...) {
std::cout << "I caught something, but I don't know what it is.";
}Industry Note: Use catch (...) sparingly. It swallows errors without letting you analyze them. It's like hearing a noise in the car and turning up the radio to ignore it.
4. Using Standard Exceptions (std::exception)
In the examples above, we threw an int and a string. In professional C++, we rarely throw primitive types.
Why? Because throw 20 doesn't tell us what happened, just that the number 20 is involved.
The Concept: The Standard Hierarchy
C++ provides a standard library header <stdexcept> containing a base class called std::exception. All professional exceptions inherit from this.
Common types you will use:
std::runtime_error: Events that cannot be predicted (e.g., file not found, network down).std::logic_error: Bugs in your code (e.g., accessing index -1 of an array).std::out_of_range: Accessing a vector past its size.
Hands-on Industry Standard 🛠️
Always throw objects derived from std::exception and catch them by reference.
Why catch by reference?
If you catch by value (catch (std::exception e)), you slice the object and trigger a copy. Catching by reference (catch (const std::exception& e)) is faster and preserves the exact error details.
Complete Professional Example
#include <iostream>
#include <stdexcept> // REQUIRED for standard exceptions
#include <vector>
// A function that simulates a database lookup
std::string getUserName(int id) {
if (id < 0) {
// Logic error: The programmer calling this made a mistake.
throw std::logic_error("ID cannot be negative.");
}
if (id > 1000) {
// Runtime error: The ID is valid integer, but user not found in DB.
throw std::runtime_error("User not found in database.");
}
return "John Doe";
}
int main() {
try {
// Try changing this to -5 or 5000 to see different errors
std::string user = getUserName(5000);
std::cout << "User: " << user << std::endl;
}
// Best Practice: Catch specific errors first
catch (const std::logic_error& e) {
std::cerr << "Code Bug Detected: " << e.what() << std::endl;
}
// Best Practice: Catch general runtime errors next
catch (const std::runtime_error& e) {
std::cerr << "System Error: " << e.what() << std::endl;
}
// Best Practice: Catch the generic parent class last (Polymorphism!)
catch (const std::exception& e) {
std::cerr << "Unknown Standard Error: " << e.what() << std::endl;
}
return 0;
}Key Takeaways from the Code:
.what(): All standard exceptions have a.what()method that returns the error message string.- Order Matters: Catch blocks are checked top-to-bottom. If you put
catch (std::exception)first, it will catch everything (since logic_error inherits from it), and the specific blocks below will be unreachable (Dead Code).
Summary 📝
- Error Codes are easy to ignore; Exceptions force you to handle the problem or crash.
- Throwing pauses execution and unwinds the stack (cleaning up memory).
- Try/Catch blocks allow you to safely recover from errors.
- Best Practice: Always throw exceptions derived from
<stdexcept>and catch them byconst reference.
Imagination Check: Think of your program as a relay race. Passing data normally is handing off the baton. Throwing an exception is realizing the baton is actually a stick of dynamite 🧨. You don't hand it off; you throw it out of the track to the safety squad (the catch block).
🔗 References & Further Reading
Challenge
You are tasked with creating a robust error handling mechanism for a data processing function.
- Define a custom exception class named
UnknownDataErrorthat publicly inherits fromstd::exception. - Override the
what()method in yourUnknownDataErrorclass. It must return the C-style string"Error: Unknown data format encountered.". Remember to mark the method asconst noexcept override. - Implement the
handleDataProcessingfunction. Inside this function, you must call the providedprocessData(data)function from within atryblock. - Following the
tryblock, addcatchblocks to handle potential exceptions. It is critical that you catch exceptions byconstreference (e.g.,const std::exception& e). - Your
catchblocks must be ordered correctly to handle the most specific exception types before their more general base classes. Handle the following exception types in this exact order:UnknownDataErrorstd::invalid_argumentstd::runtime_error
- Inside each
catchblock, print the message returned by the exception's.what()method tostd::cout, followed by a newline character.
Expected result
Your code should produce the following output, with each line corresponding to a call in the main function. This demonstrates that both the successful case and each specific exception type are handled correctly.
Data processed successfully.
Error: Data cannot be empty.
Error: Unknown data format encountered.
Error: Corrupt data packet detected.