`try` — C++ Keyword
`try` — C++ Keyword
The try keyword in C++: marks a block whose exceptions are handled by following catch clauses.
`try` — C++ Keyword
The try keyword in C++: marks a block whose exceptions are handled by following catch clauses.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
tryMarks a block of code whose exceptions will be handled by one or more catch clauses directly following it.
try {
// code that may throw
} catch (exception-declaration) {
// handler
}
// Function-try-block (constructor/function level)
Type func() try { body } catch (exception-declaration) { handler }
#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
}
}
try block must be followed by at least one catch clause.std::terminate is called.try/catchint 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;
}