Thuta Learning
C++
AdvancedProgrammingBeginner

Exceptions (Try...Catch)

C++Lesson 2435 min

What you'll walk away with

  • Throw a standard exception from a function and handle it in the caller with try/catch
  • Explain why exceptions are thrown by value and caught by const reference
  • Pick the right type from the std::exception hierarchy and order catch clauses from specific to general
  • Predict how RAII objects release resources during stack unwinding
  • State what noexcept means and why exceptions must never escape a destructor

Explain it simply

Explain it simply

In a restaurant, when the cook discovers there is no chicken left, they tell the waiter or the manager. The cook does not walk to the table to renegotiate the order; they pass the problem to someone who can deal with it.

In C++ that hand-off is called throwing. A function that cannot continue throws an exception object and stops immediately. Further up, the calling code marks a region with a try block, meaning "something in here might fail", and a catch block catches the exception and handles it.

Problem → Why → Solution

The problem: error codes that nobody checks

Without exceptions, a common style is to return a special value such as -1 on error. parsePort() below dutifully returns -1 for bad text. The trouble is that the caller forgets to check: the program carries on and tries to start a server on port -1.

error_code.cpp
#include <iostream>
#include <string>

// Returns the port, or -1 when the text is not a valid port number.
int parsePort(const std::string& text) {
    if (text.empty() || text.size() > 5) return -1;
    for (char c : text) if (c < '0' || c > '9') return -1;
    int port = std::stoi(text);
    return (port >= 1 && port <= 65535) ? port : -1;
}

void startServer(int port) { std::cout << "listening on port " << port << '\n'; }

int main() {
    int port = parsePort("80a");
    startServer(port);        // nobody checked: "listening on port -1"
}

Why do error codes slip through so easily?

The compiler never forces you to check a return value, so forgetting raises no error and the program runs on with bad data. In a deep call chain every layer must check the code and pass it upward by hand, and functions with no return value, such as constructors, cannot return an error code at all. An exception cannot be ignored silently: if nobody catches it, the program stops instead of continuing with bad data.

Core concept: throw, stack unwinding, catch

When a throw expression runs, it creates an exception object and skips the rest of the current function. The runtime then walks back up the call stack toward the callers, destroying the local objects of every function it leaves by calling their destructors; this is stack unwinding. It continues until it finds a try block with a catch handler that matches the exception's type, and runs that handler. If no handler exists anywhere, std::terminate is called and the program ends.

Throw by value and catch by const reference: throw std::invalid_argument("..."); paired with catch (const std::exception& e). Catching by value copies the exception and slices off the derived part, so e.what() can no longer report the real message. A reference makes no copy and keeps the object's dynamic type, so the virtual what() returns the actual message.

Exception typeDerives fromTypical cause
std::invalid_argumentstd::logic_errorAn argument that breaks the function's rules
std::out_of_rangestd::logic_errorvector::at() with a bad index
std::runtime_errorstd::exceptionProblems only visible at runtime (network, files)
std::bad_allocstd::exceptionnew could not get memory

Catch clauses are tried from top to bottom, and only the first match runs. A derived type also matches a handler for its base, so put specific (derived) types first and const std::exception& last. catch (...) catches anything, and writing throw; inside a handler rethrows the current exception with its original type. When you need your own exception type, derive it from a standard class such as std::runtime_error so const std::exception& handlers can still catch it.

Do not use exceptions for ordinary, expected outcomes such as the end of a loop or a user choosing "no". Keep them for genuine failures where a function cannot do its job: invalid input, a missing file, a constructor that cannot establish its invariant.

Mental model: throw, unwind, catch
  1. Detect a failure, throw an object
  2. Unwind: skip code, destroy locals
  3. Match catch clauses top to bottom
  4. Handle once, at the right level

Throw where the failure happens and catch where a real decision can be made; the functions in between need no extra code.

General pattern

cpp
Result mightFail(Input value) {
    if (cannotSucceed(value))
        throw std::runtime_error("what went wrong");   // throw by value
    return result;
}
try {
    use(mightFail(input));
} catch (const SpecificError& e) {      // most specific type first
    handle(e);
} catch (const std::exception& e) {     // catch by const reference
    report(e.what());
}

When a function cannot continue, it throws a standard exception type. The caller makes the call inside a try block and catches the specific type first and std::exception last, always by const reference.

Example: an age check

In this example checkAge() throws std::invalid_argument when the age is under 18. Watch the exception cross the function boundary into the catch in main(), and notice that the "Access granted." line is skipped.

exceptions.cpp
#include <iostream>
#include <stdexcept>
using namespace std;

void checkAge(int age) {
    if (age < 18) {
        throw invalid_argument("You must be at least 18 years old.");
    }
}

int main() {
    try {
        int age = 15;
        checkAge(age);
        cout << "Access granted." << endl;
    } catch (const invalid_argument& e) {
        cout << "Access denied: " << e.what() << endl;
    }
    return 0;
}

Code breakdown

  1. Line 2#include <stdexcept>

    This header declares the standard exception classes such as std::invalid_argument and std::runtime_error.

  2. Line 7throw invalid_argument("You must be at least 18 years old.");

    Builds the exception object by value and throws it. checkAge() stops right here; it does not return normally, unwinding begins instead.

  3. Lines 14-15checkAge(age);

    The exception comes back out of checkAge() into main()'s try block. The next line, "Access granted.", never runs.

  4. Line 16} catch (const invalid_argument& e) {

    The type matches, so this handler runs. It is a const reference, so nothing is copied and nothing is sliced.

  5. Line 17e.what()

    what() is a virtual member function of std::exception that returns the message given to the constructor, so the program prints "Access denied: You must be at least 18 years old.".

You should see
Access denied: You must be at least 18 years old.
What happens after throw
  1. throw creates the exception object
  2. The rest of checkAge() is skipped
  3. Locals are destroyed while unwinding
  4. The first matching catch runs

A handler matches

catch runs, program continues

No handler anywhere

std::terminate ends the program

The standard hierarchy and catch order

The standard library throws exceptions too: vector::at() throws std::out_of_range for a bad index, and std::stoi() throws std::invalid_argument for text that is not a number. The program below orders three catch clauses from specific to general. invalid_argument derives from logic_error, so the second handler catches it.

hierarchy.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

void run(int test) {
    std::vector<int> scores{90, 75};
    if (test == 0) std::cout << scores.at(5) << '\n';        // out_of_range
    if (test == 1) std::cout << std::stoi("abc") << '\n';    // invalid_argument
    if (test == 2) throw std::runtime_error("database is offline");
}

int main() {
    for (int test = 0; test < 3; ++test) {
        try {
            run(test);
        } catch (const std::out_of_range&) {
            std::cout << "index problem\n";
        } catch (const std::logic_error&) {
            std::cout << "logic error\n";
        } catch (const std::exception& e) {
            std::cout << "other error: " << e.what() << '\n';
        }
    }
}

The output is "index problem", "logic error" and "other error: database is offline". The what() messages from at() and stoi() differ between standard library implementations, so this program does not print them. Move the const std::exception& handler to the top and it swallows everything, and g++ warns that the later handlers "will be caught by earlier handler".

RAII: cleanup that survives exceptions

Stack unwinding calls the destructors of local objects, so RAII classes that release their resource in the destructor guarantee cleanup whether or not an exception occurs (lesson 16). The Connection below opens in its constructor and closes in its destructor. The output shows db being closed even when saveOrder(-1) throws.

raii_unwinding.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>

class Connection {
public:
    explicit Connection(std::string name) : name_(std::move(name)) {
        std::cout << "open " << name_ << '\n';
    }
    ~Connection() { std::cout << "close " << name_ << '\n'; }

private:
    std::string name_;
};

void saveOrder(int id) {
    Connection db("orders-db");
    if (id < 0) throw std::invalid_argument("negative order id");
    std::cout << "saved order " << id << '\n';
}

int main() {
    try {
        saveOrder(7);
        saveOrder(-1);
        saveOrder(8);            // never reached
    } catch (const std::exception& e) {
        std::cout << "error: " << e.what() << '\n';
    }
}

The output is "open orders-db", "saved order 7", "close orders-db", "open orders-db", "close orders-db" and "error: negative order id". Notice the second "close" appears before the handler runs: unwinding destroys the locals before control reaches the catch. Hand-written new and delete, by contrast, get skipped when a throw happens between them and the memory leaks, which is why ownership belongs in RAII types such as std::unique_ptr.

noexcept and destructors

Marking a function noexcept promises that no exception will ever leave it. Break the promise and std::terminate is called, ending the program. The promise matters for performance as well: when std::vector grows its memory, it moves elements instead of copying them only if their move constructor is noexcept.

Destructors are noexcept by default, even when you do not write it. An exception escaping a destructor therefore calls std::terminate, and g++ warns "'throw' will always call 'terminate'". The rule exists because two exceptions cannot be in flight at once during unwinding. If cleanup in a destructor can fail, catch and log the failure inside it, and if callers need to hear about the error, offer a separate close() function that may throw.

noexcept.cpp
#include <iostream>
#include <string>
#include <type_traits>

int add(int a, int b) noexcept { return a + b; }
int parse(const std::string& text) { return std::stoi(text); }

struct Widget {
    ~Widget() {}        // destructors are noexcept unless you say otherwise
};

int main() {
    std::cout << std::boolalpha;
    std::cout << "add: " << noexcept(add(1, 2)) << '\n';
    std::cout << "parse: " << noexcept(parse("7")) << '\n';
    std::cout << "~Widget: " << std::is_nothrow_destructible_v<Widget> << '\n';
}

The noexcept(expression) operator checks at compile time, without running the expression, whether it can throw. The output is "add: true", "parse: false" and "~Widget: true"; note the last one is true although Widget's destructor never says noexcept.

In real projects

Where this shows up in real projects

Web servers commonly wrap each request handler in an outermost catch (const std::exception& e). When one request fails, the error is logged, the client gets an HTTP 500, and the server keeps running. Inner functions do not need to know the handler exists; they just throw where the problem occurs. Because database connections, files and locks are held by RAII objects, a failed request never leaks resources.

Some codebases avoid exceptions entirely: the Google C++ Style Guide, for example, decided against them, and some embedded systems and game engines compile with -fno-exceptions. Those projects use error codes, std::optional, or C++23's std::expected instead. Whichever approach you choose, apply it consistently across the whole project.

Common mistakes

Common mistakes

1. Catching by value

catch (std::exception e) copies the exception and slices it. g++ -Wall warns "catching polymorphic type 'class std::exception' by value [-Wcatch-value=]", and with GCC's standard library the copy's what() returns just "std::exception" instead of the real message. Always write catch (const std::exception& e).

2. Putting the general handler first

Placing catch (const std::exception&) above catch (const std::invalid_argument&) means the first handler grabs every invalid_argument and the second never runs. g++ warns "exception of type 'std::invalid_argument' will be caught by earlier handler [-Wexceptions]". List derived types first.

3. Throwing from a destructor

~Connection() { throw std::runtime_error("close failed"); } calls std::terminate because destructors are implicitly noexcept, ending the program on the spot. g++ warns "'throw' will always call 'terminate' [-Wterminate]". Catch and log the error inside the destructor instead.

4. Throwing strings or ints

throw std::string("failed"); or throw 42; is legal, but neither derives from std::exception, so generic handlers such as catch (const std::exception&) miss them and there is no what(). Throw a standard exception type, or your own class derived from one.

Best practices

Best practices

  • Throw exceptions by value and catch them by const reference.
  • Catch only where you can actually handle the error, and never leave an empty catch block that swallows it.
  • Hold every resource in an RAII object instead of cleaning up by hand.
  • Keep move constructors, swap and destructors noexcept and make sure they cannot throw.

Mini challenge

Mini challenge: validating a port with exceptions

Rewrite parsePort(), which reads a port number from text, to report errors with exceptions instead of error codes, and try it on five inputs.

  • Throw std::invalid_argument for empty text or any non-digit character
  • Throw std::out_of_range for values outside 1 to 65535, including text longer than 5 digits
  • main() calls it for each input inside try and catches the two exception types separately, by const reference
  • Finally, print how many inputs were accepted
ports.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

int parsePort(const std::string& text) {
    // TODO: empty text           -> std::invalid_argument("empty input")
    // TODO: a non-digit character -> std::invalid_argument("'<text>' is not a number")
    // TODO: outside 1..65535      -> std::out_of_range("<text> is outside 1-65535")
    // TODO: otherwise return the port
}

int main() {
    const std::vector<std::string> inputs{"8080", "80a", "70000", "", "0"};
    // TODO: for each input: try parsePort, print "port N" or the error,
    //       catching invalid_argument and out_of_range separately
    // TODO: print "<accepted> of <total> inputs accepted"
}

Expected: The program prints: port 8080 invalid: '80a' is not a number out of range: 70000 is outside 1-65535 invalid: empty input out of range: 0 is outside 1-65535 1 of 5 inputs accepted

Show hint

Check that every character is between '0' and '9' before calling std::stoi, because std::stoi("80a") returns 80 without throwing. Throwing out_of_range for text longer than 5 characters before calling stoi also avoids any int overflow.

Show solution
ports.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

int parsePort(const std::string& text) {
    if (text.empty()) throw std::invalid_argument("empty input");
    for (char c : text) {
        if (c < '0' || c > '9') {
            throw std::invalid_argument("'" + text + "' is not a number");
        }
    }
    if (text.size() > 5) throw std::out_of_range(text + " is outside 1-65535");
    int port = std::stoi(text);
    if (port < 1 || port > 65535) throw std::out_of_range(text + " is outside 1-65535");
    return port;
}

int main() {
    const std::vector<std::string> inputs{"8080", "80a", "70000", "", "0"};
    int accepted = 0;
    for (const auto& input : inputs) {
        try {
            int port = parsePort(input);
            std::cout << "port " << port << '\n';
            ++accepted;
        } catch (const std::invalid_argument& e) {
            std::cout << "invalid: " << e.what() << '\n';
        } catch (const std::out_of_range& e) {
            std::cout << "out of range: " << e.what() << '\n';
        }
    }
    std::cout << accepted << " of " << inputs.size() << " inputs accepted\n";
}

Quick quiz 1 / 3

What does try { std::cout << "A"; throw std::runtime_error("x"); std::cout << "B"; } catch (const std::exception&) { std::cout << "C"; } std::cout << "D"; print?

Quick quiz 2 / 3

Which catch clause is best for catching a std::runtime_error?

Quick quiz 3 / 3

What happens when an exception leaves a function marked noexcept?

What to remember

  • throw stops the function, unwinds the stack and looks for the first matching catch; with none, std::terminate is called.
  • Throw standard exception types by value and catch them by const reference, from specific to general.
  • Unwinding runs the destructors of local objects, so RAII guarantees cleanup even when exceptions fly.
  • Breaking noexcept calls std::terminate, and destructors are noexcept by default, so exceptions must never escape them.

C++ Core Guidelines — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exceptions (Try...Catch) | Thuta Learning