C++ Programming

Exception Handling

Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.

On this page

Exception Handling

Exception handling allows programs to deal with errors gracefully instead of crashing. It's essential for writing robust, production-quality C++ code.

What are Exceptions?

Exceptions are runtime errors or unusual conditions that disrupt normal program flow. Instead of crashing, exceptions can be caught and handled.

Benefits:

  • Error Recovery: Handle errors without crashing
  • Clean Code: Separate error handling from business logic
  • Resource Safety: Ensure cleanup even when errors occur
  • Information Propagation: Pass error information up call stack

Exception Handling Syntax

Basic try-catch Block

1try {
2    // Code that might throw exception
3    riskyFunction();
4} catch (exception_type e) {
5    // Handle exception
6    cout << "Error: " << e.what() << endl;
7}

Sample Output

Error:

Example

1#include <iostream>
2#include <stdexcept>
3using namespace std;
4 
5int divide(int a, int b) {
6    if (b == 0) {
7        throw runtime_error("Division by zero!");
8    }
9    return a / b;
10}
11 
12int main() {
13    try {
14        int result = divide(10, 0);
15        cout << "Result: " << result << endl;
16    } catch (runtime_error& e) {
17        cout << "Caught: " << e.what() << endl;
18    }
19    return 0;
20}

Sample Output

Result: 
Caught:

Standard Exception Classes

C++ provides standard exception hierarchy:

1exception
2├── logic_error
3│   ├── invalid_argument
4│   ├── domain_error
5│   ├── length_error
6│   └── out_of_range
7├── runtime_error
8│   ├── range_error
9│   ├── overflow_error
10│   ├── underflow_error
11│   └── system_error
12└── bad_alloc (from new)

Using Standard Exceptions

1#include <stdexcept>
2 
3// Invalid argument
4if (value < 0) {
5    throw invalid_argument("Value must be non-negative");
6}
7 
8// Out of range
9if (index >= size) {
10    throw out_of_range("Index out of bounds");
11}
12 
13// Runtime error
14if (fileNotFound) {
15    throw runtime_error("File not found");
16}

Multiple catch Blocks

Handle different exception types:

1try {
2    // Code that might throw
3} catch (invalid_argument& e) {
4    // Handle invalid argument
5} catch (out_of_range& e) {
6    // Handle out of range
7} catch (exception& e) {
8    // Handle any other exception
9}

Order Matters: More specific exceptions first, general last.

Exception Propagation

Exceptions propagate up the call stack until caught:

1void function3() {
2    throw runtime_error("Error in function3");
3}
4 
5void function2() {
6    function3();  // Exception propagates
7}
8 
9void function1() {
10    try {
11        function2();
12    } catch (runtime_error& e) {
13        cout << "Caught: " << e.what() << endl;
14    }
15}

Sample Output

Caught:

Creating Custom Exceptions

Derive from standard exception classes:

1class MyException : public runtime_error {
2public:
3    MyException(const string& msg) : runtime_error(msg) {}
4};
5 
6// Usage
7throw MyException("Custom error message");

Exception Specifications (Deprecated)

Old Style (C++98):

1void function() throw(runtime_error);  // Deprecated!

Modern Style (C++11):

1void function() noexcept;  // No exceptions
2void function() noexcept(false);  // May throw

RAII and Exception Safety

RAII (Resource Acquisition Is Initialization) ensures resources are cleaned up even when exceptions occur.

Without RAII (Problem)

1void badFunction() {
2    int* ptr = new int(10);
3    riskyOperation();  // If this throws, memory leak!
4    delete ptr;
5}

With RAII (Solution)

1void goodFunction() {
2    unique_ptr<int> ptr = make_unique<int>(10);
3    riskyOperation();  // If this throws, ptr automatically deleted!
4}

Exception Safety Guarantees

  1. Basic Guarantee: No resource leaks, valid state
  2. Strong Guarantee: Operation succeeds or state unchanged
  3. No-throw Guarantee: Never throws exceptions

noexcept Specifier

Mark functions that don't throw:

1void safeFunction() noexcept {
2    // This function promises not to throw
3}
4 
5// Conditional noexcept
6template <typename T>
7void swap(T& a, T& b) noexcept(noexcept(a.swap(b))) {
8    a.swap(b);
9}

Best Practices

  1. ✅ Use exceptions for exceptional conditions
  2. ✅ Catch by reference (not by value)
  3. ✅ Use specific exception types when possible
  4. ✅ Don't throw from destructors (undefined behavior)
  5. ✅ Use RAII for resource management
  6. ✅ Document exceptions in function comments
  7. ✅ Catch specific exceptions first, general last
  8. ✅ Re-throw with `throw;` to preserve stack trace

Common Patterns

Pattern 1: Resource Guard

1class FileGuard {
2    FILE* file;
3public:
4    FileGuard(const char* name) : file(fopen(name, "r")) {
5        if (!file) throw runtime_error("Cannot open file");
6    }
7    ~FileGuard() { if (file) fclose(file); }
8    FILE* get() { return file; }
9};

Pattern 2: Exception Wrapper

1template <typename Func>
2auto safeCall(Func f) {
3    try {
4        return f();
5    } catch (exception& e) {
6        cout << "Error: " << e.what() << endl;
7        throw;  // Re-throw
8    }
9}

Sample Output

Error:

Common Mistakes

  • ❌ Catching by value instead of reference
  • ❌ Catching exception before specific types
  • ❌ Throwing from destructors
  • ❌ Swallowing exceptions silently
  • ❌ Using exceptions for control flow
  • ❌ Not cleaning up resources in catch blocks
  • ❌ Forgetting to re-throw when needed

Exception vs Error Codes

AspectExceptionsError Codes
PerformanceSlower (when thrown)Fast
VisibilityMust be handledEasy to ignore
InformationRich (what(), type)Limited
Control FlowAutomatic propagationManual checking
Use CaseExceptional conditionsExpected errors

Next Module

In Module 14, we'll learn about File I/O - reading and writing files in C++!

Hands-on Examples

Basic Exception Handling

#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw runtime_error("Division by zero is not allowed!");
    }
    return a / b;
}

int getElement(int arr[], int size, int index) {
    if (index < 0 || index >= size) {
        throw out_of_range("Index out of bounds!");
    }
    return arr[index];
}

int main() {
    // Example 1: Division by zero
    cout << "=== Example 1: Division ===" << endl;
    try {
        int result = divide(10, 0);
        cout << "Result: " << result << endl;
    } catch (runtime_error& e) {
        cout << "Caught exception: " << e.what() << endl;
    }
    
    // Example 2: Array bounds
    cout << "\n=== Example 2: Array Access ===" << endl;
    int arr[] = {10, 20, 30, 40, 50};
    try {
        int value = getElement(arr, 5, 10);  // Invalid index
        cout << "Value: " << value << endl;
    } catch (out_of_range& e) {
        cout << "Caught exception: " << e.what() << endl;
    }
    
    // Example 3: Successful operation
    cout << "\n=== Example 3: Success ===" << endl;
    try {
        int result = divide(20, 4);
        cout << "Result: " << result << endl;
        
        int value = getElement(arr, 5, 2);
        cout << "Array value: " << value << endl;
    } catch (exception& e) {
        cout << "Caught: " << e.what() << endl;
    }
    
    return 0;
}

Basic exception handling uses try-catch blocks. Code that might throw is in try block. catch blocks handle specific exception types. Exceptions propagate up call stack until caught. Use standard exception types from <stdexcept>. Always catch by reference, not by value.

Sample Output

=== Example 1: Division ===
Caught exception: Division by zero is not allowed!

=== Example 2: Array Access ===
Caught exception: Index out of bounds!

=== Example 3: Success ===
Result: 5
Array value: 30