> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C++ Catch Clause

A `catch` clause is an exception handler that immediately follows a `try` block or a function-try-block. It executes when an exception of a matching type is thrown during the execution of that associated block. It intercepts the exception object, halts the stack unwinding process for that specific exception, and provides a scoped block to resolve the error state or delegate it further up the call stack.

## Syntax and Handler Ordering

A `try` block must be followed by one or more `catch` clauses. The C++ runtime evaluates `catch` clauses strictly in the sequential order they are declared. Hierarchical ordering is critical: handlers for derived classes must appear before handlers for their respective base classes. If a base class handler precedes a derived class handler, the base class handler intercepts all derived exceptions, rendering the derived handler unreachable.

The ellipsis syntax `catch (...)` acts as a universal fallback, matching any exception type regardless of its origin or type signature. Because there is no type declaration, the exception object cannot be bound to an identifier. The catch-all handler must always be the final clause in a `try-catch` sequence.

```cpp theme={"dark"}
#include <iostream>
#include <stdexcept>
#include <exception>

class SpecificException : public std::runtime_error {
public:
    SpecificException() : std::runtime_error("Specific error state") {}
};

int main() {
    try {
        throw SpecificException();
    } 
    catch (const SpecificException& e) {
        // Derived class: Evaluated first
        std::cerr << "Caught specific exception: " << e.what() << '\n';
    } 
    catch (const std::exception& e) {
        // Base class: Evaluated second
        std::cerr << "Caught standard exception: " << e.what() << '\n';
    } 
    catch (...) {
        // Catch-all handler: Evaluated last
        std::cerr << "Caught unknown exception\n";
    }
    return 0;
}
```

## Type Matching Rules

A `catch` clause matches the thrown exception if any of the following conditions are met:

1. **Exact Match:** The handler type is the exact same type as the exception object, ignoring top-level `const` and `volatile` (cv-qualifiers).
2. **Base Class Match:** The handler type is an unambiguous, **public** base class of the exception object's type (caught via reference or value). The C++ runtime exception matcher does not consider the access control context at the `throw` point; private or protected base classes will never match.
3. **Pointer and Qualification Conversions:** The handler type is a pointer, and the thrown exception is a pointer that can be implicitly converted to the handler's type via standard pointer conversions (e.g., derived pointer to public base pointer, or any non-const pointer to `void*`) or **qualification conversions** (e.g., throwing an `int*` and catching it via a `const int*` handler).

*Note: Standard implicit type conversions (such as `int` to `double`) are not performed during exception matching.*

## Binding Mechanisms

The parameter declaration in the `catch` clause dictates how the exception object is bound to the handler:

* **By Reference (`catch (const T& e)` or `catch (T& e)`):** Binds directly to the thrown object. This preserves the dynamic type of the exception and prevents object slicing when catching derived exceptions via a base class reference.
* **By Value (`catch (T e)`):** Invokes the copy constructor to create a local copy of the exception object. If a derived exception is caught by a base class value, object slicing occurs, and the derived-specific data and overridden methods are lost.
* **By Pointer (`catch (T* e)`):** Matches exceptions thrown as pointers, arrays, or functions (which decay to pointers during the throw expression), as well as `std::nullptr_t` (which implicitly converts to a pointer).
* **Anonymous (`catch (T)` or `catch (const T&)`):** Matches the type, but omits the identifier. The exception is caught, but the object itself cannot be inspected or manipulated within the block.
* **Rvalue References (Forbidden):** Catching by rvalue reference (e.g., `catch (T&& e)`) is explicitly forbidden by the C++ standard. Attempting to do so makes the program ill-formed and will result in a compilation error.

## Re-throwing Exceptions

Within a `catch` block, the exception currently being handled can be propagated further up the call stack using the `throw` keyword without an operand. Using `throw;` re-throws the exact original exception object, preserving its dynamic type. Conversely, using `throw e;` throws a new exception based on the static type of `e` within the catch block, which causes object slicing if `e` is a base class reference to a derived exception.

```cpp theme={"dark"}
#include <iostream>
#include <stdexcept>

int main() {
    try {
        try {
            throw std::runtime_error("Initial error");
        }
        catch (const std::exception& e) {
            // Re-throws the exact original exception object
            throw; 
        }
    }
    catch (...) {
        std::cerr << "Caught the re-thrown exception\n";
    }
    return 0;
}
```

## Function-Try-Blocks

A function-try-block associates a sequence of `catch` clauses with the entire body of a function, including the constructor initializer list. This is a critical mechanism, as it is the only way to catch exceptions thrown during the initialization of base classes or non-static data members in a constructor.

When an exception is caught in a function-try-block of a constructor or destructor, the exception is implicitly re-thrown at the end of the `catch` handler.

```cpp theme={"dark"}
#include <iostream>
#include <stdexcept>

class Member {
public:
    Member() {
        throw std::runtime_error("Member initialization failed");
    }
};

class Container {
    Member m;
public:
    // Function-try-block syntax
    Container() try : m() {
        // Constructor body
    } 
    catch (const std::exception& e) {
        std::cerr << "Caught in function-try-block: " << e.what() << '\n';
        // The exception is implicitly re-thrown here
    }
};

int main() {
    try {
        Container c;
    } 
    catch (const std::exception& e) {
        std::cerr << "Caught re-thrown exception in main: " << e.what() << '\n';
    }
    return 0;
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C++ Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
