C++

C++ Exceptions: try, catch, and throw, With the Program Still Running After

An exception is how a C++ program reports an error it cannot fix where it happened. This guide runs three programs. The main program throws a std::runtime_error from inside a divide function, catches it, and prints caught: divide by zero, then catches a thrown int and prints caught int=42, then prints after catch, program continues. A second program catches the std::out_of_range that a vector .at() call throws, and shows catch (...) receiving an int throw with no type and no message. A third shows catch by value slicing a derived exception down to its base type, while catch by const reference keeps the whole object.

Written November 11, 2026 · 8 min read

By the end of this guide
  • The main program: a throw, two catches, and a program that continues
  • throw: an exception is a value in flight
  • try and catch: the handler runs, then execution continues
  • Catch by const reference, not by value

What this guide is

Most functions report trouble in one of two ways. They can return a code or a special value, and trust every caller to check it. Or they can throw an exception, which stops the normal flow at once and hands the error to a handler somewhere up the call chain. Throwing is the right tool when the code that spots the problem is not the code that can decide what to do about it: a divide function knows the divisor is zero, but only its caller knows whether to retry, substitute a value, or stop. This guide runs one main program that throws and catches two different exception types, plus two smaller programs that isolate handler selection and the slicing trap.

The main program: a throw, two catches, and a program that continues

C++
#include <iostream>
#include <stdexcept>
double divide(double a, double b) {
    if (b == 0) throw std::runtime_error("divide by zero");
    return a / b;
}
int main() {
    try {
        std::cout << "10/2=" << divide(10, 2) << "\n";
        std::cout << "10/0=" << divide(10, 0) << "\n";
    } catch (const std::runtime_error& e) {
        std::cout << "caught: " << e.what() << "\n";
    }
    try {
        throw 42;
    } catch (int code) {
        std::cout << "caught int=" << code << "\n";
    }
    std::cout << "after catch, program continues\n";
    return 0;
}

The exact output:

Output
10/2=5
10/0=caught: divide by zero
caught int=42
after catch, program continues

Read the second line closely. The program printed the 10/0= label, then called divide(10, 0), which threw before any quotient existed. The rest of that output statement never ran, so the line ends with the catch block's text instead of a number: 10/0=caught: divide by zero. The sections below take the three keywords in turn: throw starts the error on its way, try marks the code that might receive one, and catch is the handler that runs when one arrives.

throw: an exception is a value in flight

The throw statement takes a value and sends it looking for a handler. In divide, the statement is throw std::runtime_error("divide by zero");. It builds a std::runtime_error object holding the message text, and that object is the exception. Any type can be thrown: the main program's second block throws the plain int value 42, and the handler receives it as the number 42. Throwing a class type from the standard exception family is the normal habit, because those types carry a message the handler can print, but the mechanism itself accepts any value.

The moment a throw executes, the current function stops. divide never reaches its return on the zero call, and the caller never receives a value it must remember to check. Control leaves the function at once and moves up the call chain, out of divide and into main, looking for a matching handler. As the stack unwinds, the automatic objects in each abandoned scope are destroyed in the normal way, so cleanup code written in destructors still runs while the error travels. If no function on the whole chain has a matching handler, the search ends at the top and the program terminates; that case has its own section below.

try and catch: the handler runs, then execution continues

A try block marks a stretch of code whose throws should be offered to the handlers written directly after it. When everything in the block completes, the handlers are skipped and execution continues after them. When a statement inside throws, the rest of the block is abandoned: in the main program, the second output statement stops halfway, and no code after the divide(10, 0) call inside that block runs at all.

Each catch clause names one type it accepts. A thrown value is offered to the clauses in the order they are written, and the first clause whose type matches runs. The match in the main program is exact on both blocks: the std::runtime_error goes to catch (const std::runtime_error& e), and the int goes to catch (int code). A clause also matches when the thrown type derives from the type it names, which is why handler order matters when a family of related types is in play; the standard-types section below shows that ordering with a real program.

Inside the handler, the caught object is available under the name the clause gives it. The first handler prints e.what(), the message stored in the exception, which is where the words "divide by zero" in the output come from. When the handler finishes, execution does not return to the point of the throw. It continues with the statement after the whole try-and-catch construct, which in the main program is the second try block, and then the final print. That final line, after catch, program continues, is the proof that a handled exception leaves the program in a normal state.

Catch by const reference, not by value

The first handler in the main program catches const std::runtime_error&, a constant reference to the thrown object. That form is the standard habit for class-type exceptions, for two reasons a third program makes visible. The program defines a ParseError type that derives from std::runtime_error and adds one field, the line number where parsing failed:

C++
#include <iostream>
#include <stdexcept>
struct ParseError : std::runtime_error {
    int line;
    ParseError(int ln) : std::runtime_error("parse failed"), line(ln) {}
};
int main() {
    try {
        throw ParseError(7);
    } catch (std::runtime_error e) {
        std::cout << "by value what=" << e.what() << "\n";
    }
    try {
        throw ParseError(7);
    } catch (const ParseError& e) {
        std::cout << "by const& what=" << e.what() << " line=" << e.line << "\n";
    }
    return 0;
}

The exact output:

Output
by value what=parse failed
by const& what=parse failed line=7

The first handler catches by value as the base type. The object it holds is a std::runtime_error, copied from just the base part of the thrown ParseError; the derived part, including the line field, was sliced off in the copy, so that handler cannot name the line at all. The compiler warns about exactly this while building the program, reporting that it is catching a polymorphic type by value. The second handler catches by constant reference as the derived type, so it holds the thrown object itself, and e.line reads 7. Catching by reference also avoids copying the exception at all. Catching by pointer is the third form and the one to skip: exceptions are not thrown as pointers in normal code, so a pointer clause would miss a value throw entirely, and a handler that did receive a pointer would own the job of deleting it.

Standard exception types and the .at() check

The standard library throws exceptions from a family rooted at std::exception (declared in <exception>); the concrete types below are declared in the <stdexcept> header the main program includes. Two members do most of the work in everyday code. std::runtime_error is the general type for failures found at run time, the one divide throws. std::out_of_range reports an index or key outside its valid range, and the standard containers throw it from their checked access function .at(). The arrays guide on this site shows std::array::at() throwing it; a second program shows the same type arriving from a std::vector, alongside the handler-ordering rule and the catch-all form:

C++
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
    std::vector<int> v = {10, 20};
    try {
        std::cout << v.at(5) << "\n";
    } catch (const std::out_of_range& e) {
        std::cout << "caught out_of_range from at()\n";
    } catch (const std::exception& e) {
        std::cout << "caught std::exception\n";
    }
    try {
        throw 42;
    } catch (const std::exception& e) {
        std::cout << "caught std::exception\n";
    } catch (...) {
        std::cout << "caught unknown: no type, no message\n";
    }
    std::cout << "handlers done\n";
    return 0;
}

The exact output:

Output
caught out_of_range from at()
caught unknown: no type, no message
handlers done

The vector holds two values, so index 5 is out of range and .at(5) throws std::out_of_range. That type derives from std::exception, so both clauses could have accepted it; the specific clause is written first and runs, and the base clause never sees it. Written the other way around, the base clause would catch every exception in the family and the specific clause below it would be dead code. The order in this program, specific before general, is the order to keep.

The second block shows the type rules from the other side. The thrown int is not part of the std::exception family at all, so the std::exception clause cannot match it. The throw falls past that clause to catch (...), the catch-all, which accepts anything and runs last here. What it can report is the subject of the trap section below.

Uncaught exceptions terminate the program

A handler is matched by searching outward from the throw. If the search reaches the top of the program with no match, the runtime calls std::terminate, and the process ends at once. There is no default handler, no error return, and no second chance to print a farewell message from normal code.

One related rule is worth knowing in the same place. A function can be marked noexcept to promise that no exception will leave it. That promise is enforced by the same mechanism: if a throw escapes a noexcept function, std::terminate is called, just as if the throw had never been caught. Mark a function noexcept only when it genuinely cannot throw, for example a simple accessor over values already in memory, and handle every failure inside it.

Trap: catch (...) hides what went wrong

Trap
The catch-all clause catch (...) matches every throw, and that reach is the trap. It receives no object, so it has no type to report and no what() message to print. The second program proves the limit in its own output: all the handler could print was a fixed string, caught unknown: no type, no message, because the handler itself knew nothing about the int it had just caught. A catch-all that prints a line like that and then carries on has hidden the error, not handled it: the program continues in a state nobody diagnosed, with the actual failure erased.

The catch-all has two sound uses, both at boundaries. A program can catch everything at its outermost layer, note that an unknown failure occurred, and end in an orderly way instead of terminating mid-operation. Or a handler can catch everything, record that something failed, and rethrow with a bare throw; statement, which sends the same exception onward to a handler that knows its type. What it should not do is swallow the throw silently and continue as if nothing happened.

Trap: throwing from a destructor while unwinding terminates

Trap
Objects destroyed during stack unwinding run their destructors while an exception is already in flight. If one of those destructors throws, the runtime is holding two live exceptions with one mechanism for carrying them, and the rule is that the program terminates through std::terminate. The same rule reaches further than it first looks: destructors are implicitly noexcept in modern C++, so a throw escaping any destructor calls terminate, unwinding or not. This rule is stated here rather than shown, because the only run that demonstrates it is a program ending in terminate. The working habit follows from the rule: a destructor does its cleanup without throwing, and when cleanup itself can fail, for example closing a file, the destructor records the failure or ignores it and leaves the reporting to a named function the caller can invoke when a handler is available.

Which handler form for which job

Job Form Why
A failure the caller can act on, found deep in a function Throw a std::runtime_error with a message, as divide does The throw reaches the caller at once and carries the reason in what()
Reading a container at an index from outside the program .at() and a catch for std::out_of_range The checked access throws a named type instead of reading unrelated memory
Several related error types with different responses Specific catch clauses first, the base std::exception clause last The first matching clause runs, so order decides which response each type gets
A class-type exception with fields of its own Catch by const& as the derived type The whole object survives; catch by value slices the derived fields off
An unknown failure at the edge of the program catch (...) to note the failure and end, or to rethrow The clause matches anything but learns nothing, so it belongs at a boundary
A function that must never fail outward Mark it noexcept and handle every failure inside it A throw escaping a noexcept function calls std::terminate

The deciding question is who can act on the failure. Throw toward that code, catch there by constant reference, and let everything else propagate.

Checklist

  • Before throwing, pick a type from the standard exception family and give it a message a handler can print. A bare value like an int carries no explanation.
  • Before writing handlers, order the clauses from the most specific type to the most general. A base-type clause written first shadows every derived clause after it.
  • Before catching a class type, write the clause as a constant reference. Catch by value copies the object and slices off any derived fields.
  • Before indexing a container with a value from input or a calculation, use .at() and catch std::out_of_range, or check the index against the size yourself.
  • Before marking a function noexcept, confirm that nothing inside it can throw. An escaping throw calls std::terminate.
  • Before writing catch (...), decide what it will do with a failure it cannot name: end the program in an orderly way, or rethrow. Continuing as if nothing failed is not a plan.
  • Before letting a destructor report an error, move the report into a named function. A throw out of a destructor calls std::terminate.

Sources

  • cppreference, throw — the throw statement, how the exception object is formed, and how the stack unwinds while a handler is sought.
  • cppreference, try block and cppreference, Handling exceptions — the try block, handler matching order, the catch-all form, and rethrowing with a bare throw.
  • cppreference, std::exception — the base of the standard exception family, the what() member, and the types derived from it.
  • Structure reference only: the learncpp page on the need for exceptions, read for how the topic is usually sequenced; no figure or wording in this guide comes from it.

Keep Exploring