Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Throwing and catching
    4. Exceptions skip the functions in between
    5. The standard exceptions
    6. Stack unwinding: RAII still cleans up
    7. Rethrowing and catching everything
    8. Your own exception types
    9. When nobody catches it
    10. noexcept: a promise not to throw
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. A general handler before a specific one
    15. A throw that skips a delete
    16. Try it yourself

    Module 5 · Errors and undefined behavior

    5.1Exceptions

    Report an error by throwing an exception and handle it with try and catch. See how the standard exception types fit together, how RAII still cleans up while an exception travels, and what noexcept promises.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Throwing and catching
    4. Exceptions skip the functions in between
    5. The standard exceptions
    6. Stack unwinding: RAII still cleans up
    7. Rethrowing and catching everything
    8. Your own exception types
    9. When nobody catches it
    10. noexcept: a promise not to throw
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. A general handler before a specific one
    15. A throw that skips a delete
    16. Try it yourself

    Key terms

    exception
    An object that reports an error. Throwing it leaves the current function and every caller up to the nearest catch that accepts its type.
    throw
    Starts an exception: throw std::runtime_error("disk full");. The rest of the function doesn't run.
    try and catch
    try { … } marks code whose exceptions you want to handle. Each catch (const T& e) { … } after it runs when an exception of type T (or a type derived from it) leaves the try block.
    std::exception and what()
    The base class of every exception the standard library throws, from <exception>. Its member function what() returns the error message as text.
    std::runtime_error and std::logic_error
    The two main families of standard exceptions, from <stdexcept>: failures outside the program's control, and mistakes in how code was called.
    stack unwinding
    While an exception travels to its catch, every local object in the functions it leaves is destroyed, newest first.
    noexcept
    Marks a function that promises never to let an exception out. If one tries, the program ends.
    std::terminate
    The function C++ calls when exception handling can't continue, such as an exception nobody catches. It ends the program.

    A function that can’t do its job has to tell its caller: a file is missing, a quality score is out of range, a line doesn’t hold a number. The return value is already busy carrying the result. An exception reports the failure on a separate path: it leaves the function at once, skips every caller that doesn’t handle it, and lands in the nearest code that does.

    In 30 seconds

    • throw std::invalid_argument("…"); stops the function and jumps to the nearest catch that accepts that type.
    • Catch by const reference, catch (const std::exception& e), and read the message with e.what().
    • On the way out, every local object is destroyed: RAII still frees everything. This is stack unwinding.
    • An exception nobody catches ends the program. So does one that tries to leave a noexcept function.

    Throwing and catching

    throw creates an exception object and starts looking for a handler. The code you want to protect goes in a try block; each catch after it says which type of exception it handles:

    #include <print>
    #include <stdexcept>
    
    int checked_quality(int score) {
        if (score < 0 || score > 93) {
            throw std::out_of_range("quality must be 0 to 93");
        }
        return score;
    }
    
    int main() {
        try {
            std::println("{}", checked_quality(40));
            std::println("{}", checked_quality(120));
            std::println("not printed");
        } catch (const std::out_of_range& e) {
            std::println("error: {}", e.what());
        }
        std::println("done");
    }

    Output

    40
    error: quality must be 0 to 93
    done

    The second call throws, so checked_quality never reaches its return, and the rest of the try block is skipped. The catch handler runs, then the program carries on after it. std::out_of_range comes from <stdexcept>; its constructor takes the message, and what() gives it back.

    Exceptions skip the functions in between

    An exception doesn’t stop at the function that called the one that threw. It keeps going up the chain of calls until some function has a matching catch. Functions in the middle don’t need any code for it:

    #include <print>
    #include <stdexcept>
    #include <vector>
    
    int read_length(int value) {
        if (value <= 0) {
            throw std::invalid_argument("read length must be positive");
        }
        return value;
    }
    
    int total_length(const std::vector<int>& values) {
        int total = 0;
        for (int v : values) {
            total += read_length(v); // no try here
        }
        return total;
    }
    
    int main() {
        try {
            std::println("{}", total_length({150, 151}));
            std::println("{}", total_length({150, -1, 151}));
        } catch (const std::invalid_argument& e) {
            std::println("bad input: {}", e.what());
        }
    }

    Output

    301
    bad input: read length must be positive

    total_length doesn’t know about errors at all. That’s the point of exceptions: the code that finds the problem and the code that can deal with it can be far apart, and nothing in between has to pass the error along.

    The standard exceptions

    Every exception the standard library throws derives from std::exception. Module 4’s Inheritance lesson explains base and derived classes; here, all you need is this: a handler for a base class also catches every type derived from it. The main families are:

    • std::logic_error: the caller broke a rule it could have checked. std::invalid_argument, std::out_of_range and std::length_error derive from it.
    • std::runtime_error: something outside the program went wrong, like a missing file or bad data. std::range_error and std::overflow_error derive from it.
    • Others thrown by the language and library, such as std::bad_alloc when new can’t get memory.

    A handler for std::logic_error catches the first group, and catch (const std::exception& e) catches all of them. Here two library calls throw std::out_of_range, and each is caught through a base class:

    #include <print>
    #include <stdexcept>
    #include <string>
    #include <vector>
    
    std::vector<int> lengths = {150, 151};
    try {
        std::println("{}", lengths.at(5));
    } catch (const std::logic_error& e) {
        std::println("caught: {}", e.what());
    }
    try {
        std::string read = "ACGT";
        std::println("{}", read.substr(10));
    } catch (const std::exception& e) {
        std::println("caught: {}", e.what());
    }

    Output

    caught: vector::_M_range_check: __n (which is 5) >= this->size() (which is 2)
    caught: basic_string::substr: __pos (which is 10) > this->size() (which is 4)

    .at() throws std::out_of_range for an index past the end, and so does substr for a start position past the end (string and string_view covers it). The messages come from GCC’s standard library; the standard only says which type is thrown, not the text.

    Key ideaThrow by value, catch by const reference

    Write throw std::runtime_error("…");, never throw new …. Catch with const T&: no copy is made, and a handler for a base class still sees the real exception, with its own message.

    Stack unwinding: RAII still cleans up

    When an exception leaves a function, that function’s local objects are destroyed, exactly as if it had returned. Their destructors run, newest first, in every function the exception passes through. This is stack unwinding, and it’s why RAII works with exceptions. A struct that prints from its destructor shows it:

    #include <print>
    #include <stdexcept>
    #include <string>
    
    struct Guard {
        std::string name;
        ~Guard() { std::println("closing {}", name); }
    };
    
    void parse(const std::string& file) {
        Guard g{file};
        throw std::runtime_error(file + ": line 3 is not a number");
    }
    
    int main() {
        try {
            Guard log{"log.txt"};
            parse("reads.txt");
        } catch (const std::exception& e) {
            std::println("error: {}", e.what());
        }
    }

    Output

    closing reads.txt
    closing log.txt
    error: reads.txt: line 3 is not a number

    Look at the order: both guards are closed before the catch body runs, because they live inside the scopes the exception left. Anything that frees itself in a destructor (a std::vector, a std::string, a std::unique_ptr, an open file) is safe when an exception goes past it. Memory you got with a bare new isn’t; the pitfalls below show that leak.

    Rethrowing and catching everything

    Sometimes a function wants to add a note to the log but can’t fix the problem. Inside a catch, a bare throw; sends the same exception on, with its original type, to the next handler up:

    #include <print>
    #include <stdexcept>
    #include <string>
    
    int parse_count(const std::string& text) {
        try {
            return std::stoi(text);
        } catch (const std::exception&) {
            std::println("while parsing {}", text);
            throw;
        }
    }
    
    int main() {
        try {
            std::println("{}", parse_count("12"));
            std::println("{}", parse_count("many"));
        } catch (const std::invalid_argument& e) {
            std::println("invalid argument: {}", e.what());
        }
    }

    Output

    12
    while parsing many
    invalid argument: stoi

    std::stoi throws std::invalid_argument when the text doesn’t start with a number, as with "many". The handler in parse_count catches the exception as a std::exception, prints a note and rethrows, and main still catches it as the std::invalid_argument it is. A handler can leave out the name (const std::exception&) when it doesn’t use the object.

    catch (...), with three dots, catches an exception of any type, even one that doesn’t derive from std::exception (C++ lets you throw an int, though you shouldn’t). You can’t see the object, so it’s useful only as a last resort, usually followed by throw; or by ending the task:

    #include <print>
    
    try {
        throw 42;
    } catch (...) {
        std::println("something failed");
    }

    Output

    something failed

    Your own exception types

    When callers need to tell your error apart from others, or need more than a message, derive a class from std::runtime_error (or std::logic_error). Pass the message to the base class’s constructor and add your own members; Constructors covers the syntax after the :.

    #include <print>
    #include <stdexcept>
    #include <string>
    
    class ParseError : public std::runtime_error {
    public:
        ParseError(const std::string& message, int line)
            : std::runtime_error(message), line_(line) {}
        int line() const { return line_; }
    
    private:
        int line_;
    };
    
    int main() {
        try {
            throw ParseError("expected a quality score", 12);
        } catch (const ParseError& e) {
            std::println("line {}: {}", e.line(), e.what());
        }
    }

    Output

    line 12: expected a quality score

    Because ParseError derives from std::runtime_error, a catch (const std::exception& e) further up still catches it and still gets the right message from what().

    When nobody catches it

    If an exception finds no matching catch anywhere, up to and including main, C++ calls std::terminate, which ends the program. GCC’s library prints the exception’s type and message first:

    #include <stdexcept>
    
    void open_reads() {
        throw std::runtime_error("reads.fq: no such file");
    }
    
    int main() {
        open_reads();
    }

    This fails when it runs

    terminate called after throwing an instance of 'std::runtime_error'
      what():  reads.fq: no such file

    By default std::terminate calls std::abort, which stops the program at once with a non-zero exit code (a Linux shell shows 134). The standard leaves it to each implementation whether the stack is unwound before that. With GCC on this platform it isn’t, so no destructors run: files aren’t closed and buffers aren’t flushed by RAII. Don’t count on cleanup for an exception nobody catches.

    So a real program usually has a main that calls the real work, catches whatever is left, prints it to standard error and returns a non-zero exit code. Catching it means the stack is unwound and every destructor runs. This one is compiled but not run here, because it exits with 1 on purpose:

    #include <cstdio>
    #include <print>
    #include <stdexcept>
    
    void run() {
        throw std::runtime_error("reads.fq: no such file");
    }
    
    int main() {
        try {
            run();
        } catch (const std::exception& e) {
            std::println(stderr, "error: {}", e.what());
            return 1;
        }
    }

    std::println(stderr, …) (with stderr from <cstdio>) prints to standard error instead of standard output.

    noexcept: a promise not to throw

    Put noexcept after a function’s parameter list to promise that no exception will leave it. The compiler can then leave out some of the unwinding bookkeeping, and some library code picks faster paths for noexcept functions: Copy and move shows why std::vector cares. Destructors are noexcept unless you say otherwise.

    The promise is enforced at run time, and harshly: if an exception tries to leave a noexcept function, C++ calls std::terminate. No catch further up gets a chance.

    #include <print>
    #include <stdexcept>
    
    int checked_length(int value) {
        if (value <= 0) {
            throw std::invalid_argument("length must be positive");
        }
        return value;
    }
    
    int length_or_zero(int value) noexcept {
        return checked_length(value);
    }
    
    int main() {
        try {
            std::println("{}", length_or_zero(-1));
        } catch (const std::exception& e) {
            std::println("never printed");
        }
    }

    This fails when it runs

    terminate called after throwing an instance of 'std::invalid_argument'
      what():  length must be positive

    The catch in main never runs. Here the throw is one call away, so only running the program shows the problem. When the throw is written directly inside a noexcept function, GCC and Clang see it and warn, so under this course’s flags it doesn’t compile.

    Mark a function noexcept only when nothing it calls can throw, or when it catches everything itself.

    Which one should I use?

    WhatWhenWhyHow
    std::invalid_argumentA caller passed a value the function can’t accept.It’s a std::logic_error: the caller could have checked first.throw std::invalid_argument("…");
    std::out_of_rangeAn index, position or key is outside the valid range.Matches what .at() and substr throw.throw std::out_of_range("…");
    std::runtime_errorSomething outside the program failed: a missing file, a malformed record.No caller could have prevented it.throw std::runtime_error("…");
    Your own typeCallers need to tell this error apart, or need extra data like a line number.Catchable on its own, and still as a std::exception.class ParseError : public std::runtime_error
    catch (const std::exception& e)At the top of the program or of one task, where you report the error and stop or skip.Catches every standard exception and yours.catch (const std::exception& e) { … e.what() … }

    Rule of thumb: throw a standard type (or one derived from it) by value, catch by const&, and catch only where you can do something useful: retry, skip the record, or report and stop. For errors that are an expected, everyday result, the next lesson’s std::expected is often a better fit.

    Under the hood

    On Linux, GCC uses table-based exceptions, often called “zero-cost”. A try block adds no instructions to the normal path. Instead, the compiler writes tables, next to the machine code, that record which destructors to run and which handler to jump to for each range of instructions. Code that never throws pays almost nothing at run time, only the space for the tables.

    Throwing is where the cost is. Here throw allocates the exception object on the heap (the standard leaves where it goes to the implementation), then the runtime walks back through the stack frames, looks up each one in the tables, runs destructors and compares types against each catch. That’s far slower than returning a value, so exceptions suit errors that are rare. A loop that throws for one record in three can spend most of its time throwing.

    The exception objects themselves are small. On this platform, a std::exception holds only a pointer used for its virtual functions (Inheritance explains that pointer), and a std::runtime_error adds one pointer to its message, stored in a shared, reference-counted block. The standard requires that copying a standard exception never throws, so a copy can’t fail while an exception is already in flight; sharing the message is how GCC’s library keeps that promise without allocating.

    #include <exception>
    #include <print>
    #include <stdexcept>
    
    std::println("std::exception: {} bytes", sizeof(std::exception));
    std::println("std::runtime_error: {} bytes", sizeof(std::runtime_error));

    Output

    std::exception: 8 bytes
    std::runtime_error: 16 bytes

    PerformanceSome projects turn exceptions off

    Games, embedded firmware and some large code bases build with -fno-exceptions. Then throw is a compile error and library functions that would throw end the program instead. Code written for those projects reports errors with return values, like the std::expected in the next lesson.

    Common pitfalls

    A general handler before a specific one

    Handlers are tried in order, and the first one that matches wins. A std::exception handler matches a std::out_of_range too, so a specific handler after it can never run. GCC and Clang warn; with warnings as errors, it doesn’t compile:

    #include <print>
    #include <stdexcept>
    #include <vector>
    
    std::vector<int> lengths = {150, 151};
    try {
        std::println("{}", lengths.at(5));
    } catch (const std::exception& e) {
        std::println("something failed");
    } catch (const std::out_of_range& e) {
        std::println("no such read");
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:10:3: error: exception of type ‘std::out_of_range’ will be caught by earlier handler [-Werror=exceptions]
       10 | } catch (const std::out_of_range& e) {
          |   ^~~~~
    main.cpp:8:3: note: for type ‘std::exception’
        8 | } catch (const std::exception& e) {
          |   ^~~~~
    cc1plus: all warnings being treated as errors

    Put the most specific handler first: std::out_of_range, then std::exception.

    A throw that skips a delete

    RAII only protects what an object owns. Memory from a bare new is freed only if the code reaches the delete, and an exception jumps right past it. LeakSanitizer reports the leak when the program exits:

    #include <print>
    #include <stdexcept>
    
    void normalize(int count) {
        float* buffer = new float[count]{};
        if (count > 3) {
            throw std::length_error("too many values");
        }
        delete[] buffer;
    }
    
    int main() {
        try {
            normalize(5);
        } catch (const std::exception& e) {
            std::println("error: {}", e.what());
        }
        std::println("carrying on");
    }

    This fails when it runs

    ERROR: LeakSanitizer: detected memory leaks
    
    Direct leak of 20 byte(s) in 1 object(s) allocated from:
        #0 operator new[](unsigned long)
        #1 normalize(int) main.cpp:5
        #2 main main.cpp:14
    
    SUMMARY: AddressSanitizer: 20 byte(s) leaked in 1 allocation(s).

    Use std::vector<float> buffer(count); instead. Its destructor runs during unwinding, so the memory is freed whichever way normalize ends.

    Common pitfallCatch by reference, not by value

    catch (std::exception e) copies only the std::exception part of the object: it’s sliced, and the copy loses the derived type. GCC warns about it (-Wcatch-value, part of -Wall), so it doesn’t compile under this course’s flags; Clang accepts it without a word. Always write const&.

    Try it yourself

    Try it yourself

    gc_fraction returns the share of G and C bases in a DNA read. It quietly counts any other letter as an A or a T, and it returns 0 for an empty read, as if it held no G or C. Make it throw std::invalid_argument for an empty read or a letter that isn’t A, C, G or T, with a message that names the letter. Then make main print the error for a bad read and carry on with the next one.

    #include <print>
    #include <string>
    #include <vector>
    
    double gc_fraction(const std::string& dna) {
        if (dna.empty()) {
            return 0.0;
        }
        int gc = 0;
        for (char base : dna) {
            if (base == 'G' || base == 'C') {
                ++gc;
            }
        }
        return static_cast<double>(gc) / static_cast<double>(dna.size());
    }
    
    int main() {
        std::vector<std::string> reads = {"GGCA", "ACGN", "", "ATAT"};
        for (const std::string& read : reads) {
            std::println("'{}': {}", read, gc_fraction(read));
        }
    }

    Expected output

    'GGCA': 0.75
    'ACGN': skipped, unexpected base N
    '': skipped, empty read
    'ATAT': 0
    Show a hint

    In gc_fraction, throw std::invalid_argument when dna is empty and when a base isn't A, C, G or T. In main, put the println for each read inside its own try, so one bad read doesn't stop the loop.

    Show a solution
    #include <format>
    #include <print>
    #include <stdexcept>
    #include <string>
    #include <vector>
    
    double gc_fraction(const std::string& dna) {
        if (dna.empty()) {
            throw std::invalid_argument("empty read");
        }
        int gc = 0;
        for (char base : dna) {
            if (base == 'G' || base == 'C') {
                ++gc;
            } else if (base != 'A' && base != 'T') {
                throw std::invalid_argument(
                    std::format("unexpected base {}", base));
            }
        }
        return static_cast<double>(gc) / static_cast<double>(dna.size());
    }
    
    int main() {
        std::vector<std::string> reads = {"GGCA", "ACGN", "", "ATAT"};
        for (const std::string& read : reads) {
            try {
                std::println("'{}': {}", read, gc_fraction(read));
            } catch (const std::invalid_argument& e) {
                std::println("'{}': skipped, {}", read, e.what());
            }
        }
    }

    Each call can now fail with std::invalid_argument. Because the try is inside the loop, a failure skips only that read: the catch prints the reason and the loop moves on to the next one. std::format builds the message with the bad letter in it.