---
name: cpp-error-handling
description: "Best practices for error handling in C++ using exceptions, return codes, and std::expected."
language: cpp
---

# C++ Error Handling

Robust error handling patterns in C++ to ensure application stability and clear diagnostics.

## Guidelines
- **Use Exceptions for Exceptional Conditions**: Don't use exceptions for normal control flow.
- **Exception Safety**: Aim for the "Strong Exception Guarantee" whenever possible (operations either succeed completely or have no effect).
- **RAII for Cleanup**: Use RAII to ensure resources are released even when an exception is thrown.
- **Don't throw from Destructors**: Destructors should never throw exceptions, as it can lead to `std::terminate` during stack unwinding.
- **Use `std::expected` or `std::optional` (C++23/C++17)**: For expected failures where exceptions might be too heavy.
- **Define Custom Exception Types**: Inherit from `std::exception` or its subclasses for better error categorization.
- **Noexcept**: Mark functions that are guaranteed not to throw with `noexcept` to allow compiler optimizations.

## Tools & Libraries
- **Standard Library Exceptions**: `std::runtime_error`, `std::invalid_argument`, etc.
- **Boost.Outcome**: For high-performance error handling without exceptions.
- **expected (C++23 standard library)**: For value-or-error return types.

## Trigger Scenarios
- When a function can fail and needs to report an error.
- When designing a library API that needs to handle edge cases gracefully.
- When debugging a crash caused by an unhandled exception.
- When a developer asks when to use exceptions vs return codes in C++.

<!-- synapsis-dsai-managed -->
