Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

catch — handling exceptions

The catch keyword introduces an exception handler associated with try. Its parameter type determines matching, while catch (...) matches any exception and must appear last.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

try {
    /* code that may throw */
} catch (const T& e) {
    /* handle a matching exception */
} catch (...) {
    /* handle any remaining exception */
}

catch defines an exception handler after a try block. It responds to an exception thrown while executing that block or functions called from it. Execution does not return to the next statement in try after throw; when the handler finishes normally, execution continues after the entire try block and its handlers.

Handlers are checked in source order; the first match executes. For class objects, the same type or an unambiguous public base class matches. Put derived-class handlers before base-class handlers. catch (...) matches any exception and must be last.

Prefer catch (const T& e) for class objects: the reference avoids copying and slicing to a base-class portion. catch (T e) catches by value. The parameter name may be omitted when unused. catch does not allow a parameter of type T&&.

Before entering a matching handler, stack unwinding destroys the relevant constructed local objects. Without a match, searching continues in surrounding try blocks of the same thread. Finding no handler, or leaving a noexcept function during this search, leads to std::terminate.

This entry targets C++23. The linked document is an evolving draft, not a frozen C++23 edition; the repository compiler flag does not attest production runtime behavior.

Examples

#include <iostream>

struct InputError {
    int value;
};

int main() {
    try {
        throw InputError{7};
        std::cout << "unreachable\n";
    } catch (const InputError& e) {
        std::cout << "caught: " << e.value << '\n';
    } catch (...) {
        std::cout << "other exception\n";
    }
    std::cout << "continued\n";
}

Result

caught: 7
continued

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources