0Pricing
C++ Academy · Lesson

try, catch, throw

Handle errors with exceptions.

try, catch, throw is a free C++ Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Signalling Errors with throw

The throw statement raises an exception, abandoning the current path and looking for a handler up the call stack.

#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw std::runtime_error("boom");
    } catch (const std::exception& e) {
        std::cout << e.what() << "\n";
    }
}

try and catch

Code that might throw goes in a try block; matching handlers follow in catch blocks.

#include <iostream>
#include <stdexcept>

int divide(int a, int b) {
    if (b == 0) throw std::invalid_argument("divide by zero");
    return a / b;
}

int main() {
    try {
        std::cout << divide(10, 0) << "\n";
    } catch (const std::invalid_argument& e) {
        std::cout << "error: " << e.what() << "\n";
    }
}

Catch by const Reference

Always catch exceptions by const&. Catching by value slices derived exceptions and copies needlessly.

Multiple catch Blocks

List handlers from most specific to most general. The first matching block runs.

#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw std::out_of_range("bad index");
    } catch (const std::out_of_range& e) {
        std::cout << "range: " << e.what() << "\n";
    } catch (const std::exception& e) {
        std::cout << "other: " << e.what() << "\n";
    }
}

Stack Unwinding

When an exception is thrown, the stack unwinds: every local object between the throw and the handler is destroyed in reverse order.

#include <iostream>
#include <stdexcept>

struct Trace {
    ~Trace() { std::cout << "unwound\n"; }
};

void f() {
    Trace t;
    throw std::runtime_error("x");
}

int main() {
    try { f(); } catch (...) { std::cout << "caught\n"; }
}

Catch-All Handler

A catch (...) block catches any exception type. Use it sparingly, usually to log and rethrow.

Rethrowing

Inside a handler, a bare throw; rethrows the current exception, preserving its type, so an outer handler can deal with it.

#include <iostream>
#include <stdexcept>

void inner() { throw std::runtime_error("deep"); }

void middle() {
    try { inner(); }
    catch (...) { std::cout << "logged\n"; throw; }   // rethrow
}

int main() {
    try { middle(); } catch (const std::exception& e) { std::cout << e.what() << "\n"; }
}

Standard Exception Hierarchy

Most standard exceptions derive from std::exception, which exposes what(). Catching std::exception handles them all.

Throw by Value, Catch by Reference

Throw temporary exception objects by value; the runtime copies them onto a safe area. Catch by reference to avoid slicing.

Exceptions vs Error Codes

Exceptions separate the error path from the happy path and cannot be silently ignored — unlike return codes. Reserve them for genuinely exceptional situations.

Uncaught Exceptions Terminate

If no handler matches, std::terminate is called and the program aborts. Always handle exceptions you expect.

Quick Check

Test your understanding of exception handling.

Recap

You learned to raise errors with throw, handle them with try/catch, and how stack unwinding destroys locals along the way. Catch by const&, order handlers specific-to-general, and rethrow with bare throw;.

Frequently asked questions

Is the “try, catch, throw” lesson free?

Yes — the full text of “try, catch, throw” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “try, catch, throw”?

Handle errors with exceptions. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “try, catch, throw” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. try, catch, throw
  2. Exception Safety
  3. noexcept Specifier
  4. Custom Exception Types
← Back to C++ Academy