Learn C++ · 10/15

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 -1 or 0) designated to indicate that a function did not complete successfully.

Scenario: Imagine you have a function readFile().

  1. If it works, it returns 1.
  2. 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 throw keyword 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.

cpp
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:

  1. denominator is 0.
  2. throw 404 is executed.
  3. The function distinctDivision stops immediately.
  4. Control shoots up to main.
  5. main doesn't handle it.
  6. 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 try block identifies a region of code where exceptions might occur.
    • A catch block follows a try block and contains the code to handle the exception.

The Syntax

You wrap dangerous code in try. You write recovery code in catch.

Practical Example

cpp
#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:

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

cpp
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:

  1. std::runtime_error: Events that cannot be predicted (e.g., file not found, network down).
  2. std::logic_error: Bugs in your code (e.g., accessing index -1 of an array).
  3. 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

cpp
#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:

  1. .what(): All standard exceptions have a .what() method that returns the error message string.
  2. 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 📝

  1. Error Codes are easy to ignore; Exceptions force you to handle the problem or crash.
  2. Throwing pauses execution and unwinds the stack (cleaning up memory).
  3. Try/Catch blocks allow you to safely recover from errors.
  4. Best Practice: Always throw exceptions derived from <stdexcept> and catch them by const 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.

  1. Define a custom exception class named UnknownDataError that publicly inherits from std::exception.
  2. Override the what() method in your UnknownDataError class. It must return the C-style string "Error: Unknown data format encountered.". Remember to mark the method as const noexcept override.
  3. Implement the handleDataProcessing function. Inside this function, you must call the provided processData(data) function from within a try block.
  4. Following the try block, add catch blocks to handle potential exceptions. It is critical that you catch exceptions by const reference (e.g., const std::exception& e).
  5. Your catch blocks 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:
    • UnknownDataError
    • std::invalid_argument
    • std::runtime_error
  6. Inside each catch block, print the message returned by the exception's .what() method to std::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.

subunit
Data processed successfully.
Error: Data cannot be empty.
Error: Unknown data format encountered.
Error: Corrupt data packet detected.
cpp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.