C++C++
IntermediateLesson 13 of 18

Error Handling: Exceptions and optional – C++

try/catch, custom exception classes, noexcept and alternatives to exceptions.

You report errors with throw and handle them with try/catch. The standard library provides classes such as std::invalid_argument, std::out_of_range, std::runtime_error; all inherit from std::exception and have what().

#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    try {
        int zahl = std::stoi("abc");
        std::cout << zahl << '\n';
    } catch (const std::invalid_argument& e) {
        std::cout << "Invalid number: " << e.what() << '\n';
    } catch (const std::exception& e) {
        std::cout << "Other error: " << e.what() << '\n';
    }
}

You derive your own error classes from std::runtime_error (or std::logic_error). Always catch exceptions by const& so that they are not copied or sliced.

#include <iostream>
#include <stdexcept>

class KontoFehler : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;
};

double abheben(double saldo, double betrag) {
    if (betrag > saldo) throw KontoFehler("Not enough funds");
    return saldo - betrag;
}

int main() {
    try {
        abheben(50, 100);
    } catch (const KontoFehler& e) {
        std::cout << "Error: " << e.what() << '\n';    // Error: Not enough funds
    }
}

There is no finally in C++ – RAII takes care of that: destructors run when leaving the block even during an exception ("stack unwinding"). For expected "no result" cases, std::optional (or std::expected since C++23) is often better than an exception.

  • Exceptions for exceptional errors, not for normal control flow
  • noexcept marks functions that do not throw (important for move operations)
  • Never throw from a destructor
  • Returning error codes/optional is cheaper in hot paths and for frequent errors
Warningcatch (std::exception e) (by value) slices derived exceptions (slicing). catch (...) catches everything but also swallows programming errors – use it only for cleanup or rethrowing (throw;).