C++20 sections · 1024 units
Open in Course

The throw Statement

Triggering exception handling

The throw statement signals an error condition by creating and throwing an exception object. Basic usage: throw runtime_error("Something went wrong"); This creates a runtime_error object and immediately exits the current function, searching for a catch block.

You can throw any type: throw 42; or throw "error"; But prefer standard exception types for consistency. runtime_error and logic_error cover most cases. Throwing unwinds the stack: local objects are destroyed, but raw pointers are not deleted.

This is why RAII (smart pointers, containers) matters for exception safety.