`catch` — C++ Keyword
`catch` — C++ Keyword
The catch keyword in C++: handles exceptions thrown within an associated try block.
`catch` — C++ Keyword
The catch keyword in C++: handles exceptions thrown within an associated try block.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
catchDefines an exception handler for a preceding try block. Multiple catch clauses are tried in order; the first with a matching type handles the exception.
try { ... }
catch (const ExceptionType& e) { /* handle */ }
catch (const AnotherType& e) { /* handle */ }
catch (...) { /* catch-all */ }
#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);
}
}
}
const reference to avoid slicing and unnecessary copies.catch (...) matches any exception; place it last.throw; (no argument) inside a catch to re-throw the current exception.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;
}