`try` — C++ Keyword

`try` — C++ Keyword

The try keyword in C++: marks a block whose exceptions are handled by following catch clauses.

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.

try

Marks a block of code whose exceptions will be handled by one or more catch clauses directly following it.

Syntax

try {
    // code that may throw
} catch (exception-declaration) {
    // handler
}

// Function-try-block (constructor/function level)
Type func() try { body } catch (exception-declaration) { handler }

Example

#include <print>
#include <stdexcept>
#include <vector>

int main() {
    try {
        std::vector<int> v = {1, 2, 3};
        v.at(10);            // throws std::out_of_range
    } catch (const std::out_of_range& e) {
        std::println("Out of range: {}", e.what());
    } catch (const std::exception& e) {
        std::println("Exception: {}", e.what());
    }

    // Nested try blocks
    try {
        try {
            throw std::runtime_error("inner");
        } catch (const std::logic_error&) {
            std::println("logic error");  // not reached
        }
        // runtime_error re-propagates to outer try
    } catch (const std::exception& e) {
        std::println("Caught: {}", e.what());  // executed
    }
}

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;
}