`catch` — C++ Keyword

`catch` — C++ Keyword

The catch keyword in C++: handles exceptions thrown within an associated try block.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

catch

Defines an exception handler for a preceding try block. Multiple catch clauses are tried in order; the first with a matching type handles the exception.

Syntax

try { ... }
catch (const ExceptionType& e) { /* handle */ }
catch (const AnotherType& e)   { /* handle */ }
catch (...)                    { /* catch-all */ }

Example

#include <print>
#include <stdexcept>

void risky(int n) {
    if (n < 0)  throw std::underflow_error("negative");
    if (n > 99) throw std::overflow_error("too large");
}

int main() {
    for (int val : {5, -1, 200}) {
        try {
            risky(val);
            std::println("{}: OK", val);
        } catch (const std::underflow_error& e) {
            std::println("{}: underflow – {}", val, e.what());
        } catch (const std::overflow_error& e) {
            std::println("{}: overflow – {}", val, e.what());
        } catch (...) {
            std::println("{}: unknown exception", val);
        }
    }
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}