Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 171 ยท Errors and Debugging

Exceptions

Learn C++ exceptions - throw, try and catch, catching by const reference, the standard exception hierarchy in stdexcept, stack unwinding with destructors, and rethrowing.

Sooner or later every program meets a situation it can't handle where it's detected: a configuration file is missing, a user types "twelve" where a number belongs, an index is out of range, memory runs out. The code that detects the problem is often deep inside a library, while the code that knows what to do about it (show a message, retry, use a default, abort the operation) is several function calls up. Exceptions connect the two: throw reports an error, the call stack unwinds automatically, and the nearest matching catch block handles it.

Exceptions are C++'s standard error mechanism. The standard library uses them (std::vector::at, std::stoi, std::optional::value, new), and so do most application frameworks. In this lesson you'll learn throw, try and catch, why you catch by const reference, the standard exception classes in <stdexcept> and when to use each, how stack unwinding runs destructors so that RAII objects clean up, how to rethrow correctly, and what happens when nobody catches an exception. Later lessons build on this one with custom exception classes, exception safety and noexcept, and alternatives to exceptions.

throw, try and catch

Three keywords do the work:

  • throw expression; creates an exception object from the expression and starts looking for a handler. The rest of the current function doesn't run.
  • try { ... } marks a block whose exceptions you want to handle.
  • catch (const Type& e) { ... } follows a try block and handles exceptions of Type (or types derived from it).

If code inside the try block throws, control jumps straight to the first matching catch. If nothing throws, all catch blocks are skipped. Either way, execution continues after the last catch.

C++ Throwing and catching an exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

With the input -5, average_speed throws before computing anything, the line printing the speed is skipped, and the catch block prints the message you passed to the exception's constructor, available through what(). With 1.5, no exception occurs and the catch block is skipped.

You can throw values of any copyable or movable type, even int or const char*, but always throw objects of a class derived from std::exception. Then every handler can call what(), and a single catch (const std::exception& e) at the top of your program catches everything the library and your code throw.

Catch by const reference, most specific first

How you write the catch parameter matters:

  • Catch by reference (const std::exception& e). Catching by value copies the exception and slices a derived exception down to the base type, losing its real type and possibly its message. Catching by pointer requires someone to delete it. References avoid both problems.
  • Order handlers from most derived to most general. The handlers are tried top to bottom, and the first match wins. catch (const std::exception&) before catch (const std::out_of_range&) makes the second unreachable (GCC warns about it).
  • catch (...) catches anything, including non-std::exception types. You can't see what was thrown, so it's mostly for logging and rethrowing, or for last-resort handlers.
C++ Handler order, catch-all and slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last block demonstrates the problem on purpose: GCC prints a warning that the exception is caught by value, and at runtime the sliced copy is a plain std::exception, so what() returns the generic std::exception instead of detailed message. In case 1, std::stoi("12abc") succeeds (it parses the leading 12), but std::stoi("abc") throws std::invalid_argument, which is caught by the std::logic_error handler. See Converting Between Strings and Numbers.

The standard exception hierarchy

All standard exceptions derive from std::exception (header <exception>). The most useful ones are in <stdexcept>:

TEXT
std::exception
โ”œโ”€โ”€ std::logic_error            bugs: a precondition was violated
โ”‚   โ”œโ”€โ”€ std::invalid_argument   an argument has an unacceptable value
โ”‚   โ”œโ”€โ”€ std::domain_error       input outside a math function's domain
โ”‚   โ”œโ”€โ”€ std::length_error       a size exceeds the maximum (vector::reserve)
โ”‚   โ”œโ”€โ”€ std::out_of_range       an index or key is out of range (at())
โ”‚   โ””โ”€โ”€ std::future_error
โ”œโ”€โ”€ std::runtime_error          problems only detectable at run time
โ”‚   โ”œโ”€โ”€ std::range_error, std::overflow_error, std::underflow_error
โ”‚   โ”œโ”€โ”€ std::system_error       OS errors with an error code (filesystem_error derives from it)
โ”‚   โ””โ”€โ”€ std::format_error       a bad std::format string at run time
โ”œโ”€โ”€ std::bad_alloc              new could not allocate memory
โ”œโ”€โ”€ std::bad_cast, std::bad_any_cast         failed dynamic_cast to a reference / any_cast
โ”œโ”€โ”€ std::bad_optional_access    optional::value() on an empty optional
โ”œโ”€โ”€ std::bad_variant_access     std::get with the wrong alternative
โ”œโ”€โ”€ std::bad_expected_access    expected::value() holding an error (C++23)
โ””โ”€โ”€ std::bad_function_call      calling an empty std::function

The two big branches carry meaning. A logic_error means the caller broke a rule they could have checked in advance, like passing a negative size; in principle, the bug can be fixed in the code. A runtime_error means something outside the program's control went wrong, like a network failure or a corrupt file. For your own errors, throw std::invalid_argument or std::out_of_range for bad arguments and std::runtime_error for everything else, or derive your own classes from them.

C++ Exceptions thrown by the standard library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The text from what() is implementation-specific (GCC's messages mention internal names like vector::_M_range_check), so never parse it or show it to end users as is. Catch the type to decide what to do, and use what() for logs. The (void) casts silence warnings about discarding results marked [[nodiscard]].

Stack unwinding: destructors still run

When an exception leaves a function, C++ unwinds the stack: it exits every scope between the throw and the matching catch, and destroys every fully constructed local object along the way, in reverse order of construction. That's the reason RAII works. A std::lock_guard, a std::unique_ptr, a std::ofstream or a std::vector releases its resource whether the function returns normally or by exception, with no finally block needed.

C++ Destructors run during stack unwinding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

For the call with -1, all four objects are destroyed before the handler prints caught, in reverse order: level3's local, the unique_ptr's heap object, level2's local, then the try-block local. Nothing leaks, even though no code mentions cleanup.

Compare that with raw resource handling: if level2 had used new Tracer(...) and a delete at the end, the exception would skip the delete and leak the object. This is the strongest argument for smart pointers and RAII.

Two consequences matter for class design:

  • If a constructor throws, the destructor of that object never runs, because the object never finished being constructed. Members and base classes that were already constructed are destroyed. So each resource should be owned by its own RAII member, not managed by hand in the constructor.
  • Destructors must not throw. If a destructor throws while the stack is already unwinding because of another exception, the program calls std::terminate. Destructors are implicitly noexcept, and Exception Safety and noexcept explains the rules.

Rethrowing and translating exceptions

Sometimes a handler can do part of the work, like logging or rolling back, but can't fully handle the error. Inside a catch block, a bare throw; rethrows the original exception object, with its real type intact, so an outer handler can deal with it.

Writing throw e; instead throws a copy of e with the static type of the handler's parameter, which slices a derived exception if you caught it through a base reference. Always rethrow with plain throw;.

You can also translate an exception: catch a low-level error and throw a different, more meaningful one. And to move an exception somewhere else (for example to another thread), std::current_exception() captures it in a std::exception_ptr, and std::rethrow_exception(ptr) throws it again later. std::async and futures use exactly this to carry exceptions across threads.

C++ throw; versus throw e; and translating errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The with_copy function fails on purpose: the copy thrown by throw e; is a plain std::exception, so the outer catch (const std::out_of_range&) never matches. When translating, C++11's std::throw_with_nested keeps the original exception attached to the new one; Custom Exception Classes shows how.

When nobody catches: std::terminate

If an exception propagates out of main (or out of a thread's function), the runtime calls std::terminate, which by default aborts the program. Whether the stack is unwound first is implementation-defined, so destructors may not run. The same happens when an exception escapes a function marked noexcept.

This example fails on purpose to show what that looks like.

C++ An uncaught exception terminates the program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC prints terminate called after throwing an instance of 'std::runtime_error' and the message from what(), then the program is aborted with a signal, and "Resource released" never appears. In real programs, wrap the body of main in a try with a final catch (const std::exception& e) that logs the error and returns a non-zero exit code, so you always get a clean message and orderly cleanup.

Using exceptions well

Exceptions are designed for errors that are rare and that the immediate caller usually can't fix. Modern compilers implement them with a "zero-cost" model: entering a try block costs nothing, but actually throwing is slow (often microseconds) because the runtime searches tables to unwind the stack. That shapes the guidelines:

  • Throw for exceptional situations, such as broken preconditions, I/O failures or resource exhaustion. Don't use exceptions for ordinary control flow, such as "item not found" in a search that often fails; return a std::optional or std::expected (see the utility types).
  • Throw by value, catch by const reference. throw std::runtime_error{"..."}; and catch (const std::runtime_error& e).
  • Throw types derived from std::exception, so a single top-level handler catches everything.
  • Catch where you can actually handle the error. Catching and ignoring (catch (...) {}) hides bugs. Let exceptions pass through code that can't do anything useful about them; RAII cleans up along the way.
  • Put useful context in the message: which file, which value, which operation.
  • Never let exceptions escape destructors, and mark functions that can't throw noexcept.
  • Know your project's policy. Some codebases, especially games and embedded systems, compile with -fno-exceptions; Error Handling Without Exceptions covers the alternatives.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In try { f(); g(); } catch (const std::exception& e) { h(); } k();, f throws a std::runtime_error. Which functions run after f?

    The throw skips the rest of the try block (g), the matching handler runs (h), and execution continues after the catch blocks (k).
  2. 2. Why should you catch exceptions by const reference instead of by value?

    A by-value handler for a base class copies only the base part of the thrown object. A reference refers to the original, complete object.
  3. 3. With handlers in the order catch (const std::exception&), then catch (const std::out_of_range&), which runs when v.at(100) throws?

    Handlers are tried top to bottom. std::out_of_range derives from std::exception, so the first handler matches and the second is unreachable.
  4. 4. A function creates a std::unique_ptr and a std::lock_guard, then calls code that throws. What happens to them?

    Stack unwinding destroys every fully constructed local object between the throw and the handler, so RAII objects always clean up.
  5. 5. Inside catch (const std::exception& e), what is the difference between throw; and throw e;?

    throw e; copies the object using the static type of e, slicing any derived type. A bare throw; rethrows the original exception.

Summary

  • throw reports an error and skips the rest of the function; try marks code to watch, and the first matching catch handles the exception, after which execution continues after the handlers.
  • Throw objects derived from std::exception by value, and catch them by const reference, most specific type first; catch (...) catches anything.
  • <stdexcept> offers logic_error (invalid_argument, out_of_range, length_error, domain_error) for broken preconditions and runtime_error (overflow_error, system_error, โ€ฆ) for run-time failures; what() returns a message meant for logs.
  • Stack unwinding destroys every local object on the way to the handler, which is why RAII types never leak; destructors must not throw.
  • Rethrow with a bare throw; (not throw e;), translate low-level errors into meaningful ones, and use std::exception_ptr to carry exceptions elsewhere.
  • An uncaught exception calls std::terminate; catch at the top of main. Use exceptions for rare errors, not normal control flow.

Next: Custom Exception Classes, where you'll design your own exception types that carry extra information about what went wrong.