C++ catch


The catch keyword introduces an exception handler, that is, a block into which control will be transferred when an exception of compatible type is thrown. The catch keyword is followed by a parenthesized exception declaration, which is similar in form to a function parameter declaration: the parameter name may be omitted, and the ellipsis ... is allowed, which matches any type. The exception handler will only handle the exception if its declaration is compatible with the type of the exception. For more details, see catching exceptions.

try {
    std::vector<int> v(N);
    // do something
} catch (const std::bad_alloc&) {
    std::cout << "failed to allocate memory for vector!" << std::endl;
} catch (const std::runtime_error& e) {
    std::cout << "runtime error: " << e.what() << std::endl;
} catch (...) {
    std::cout << "unexpected exception!" << std::endl;