AgentSkillsCN

m06-error-handling

精通 C++ 错误处理。触发点:异常、try-catch、noexcept、std::expected、std::optional、错误码、assert、terminate。

SKILL.md
--- frontmatter
name: m06-error-handling
description: "Mastering C++ Error Handling. Triggers: exceptions, try-catch, noexcept, std::expected, std::optional, error codes, assert, terminate."

C++ Error Handling

Core Question

Is this error recoverable?

  • Yes (Local): std::expected or return code.
  • Yes (Distant): Exceptions (throw).
  • No (Bug): assert or std::terminate.

Error → Design Question

IssueDesign Question
Uncaught ExceptionDid you forget to catch, or throw in noexcept?
Silent FailureDid you ignore a return code? (Use [[nodiscard]]).
Destructor ThrowNever throw from destructor (std::terminate).

Thinking Prompt

  1. Is absence valid?

    • Yes? → std::optional<T>.
  2. Does caller need details?

    • Yes? → std::expected<T, E> or Exception.
    • No? → bool or std::optional.
  3. Is it a Logic Error (Bug)?

    • Yes? → assert() or std::terminate(). Do not throw for bugs in C++ (Contract Violation).

Trace Up / Down

  • Trace Up:
    • Issue: "Program aborted with 'terminate called recursively'."
    • Cause: An exception was thrown while stack unwinding (in a destructor).
    • Fix: Fix the destructor. Ensure RAII cleanup is noexcept.

Quick Reference

MechanismCost (Happy)Cost (Sad)Use When
std::optionalBranchBranchReturn may be empty.
std::expectedBranchBranchRecoverable error (Parsing).
ExceptionZeroHugeRare IO/Resource errors.
AssertZero (Release)AbortLogic bugs / Invariants.