C++ · Advanced level

Advanced level · Module 3: Modern C++17 and C++20 Features · Lesson 4 of 4

Choosing an Error-Handling Strategy

Compare exceptions, optional/variant results, error codes and assertions, and choose consistently for a code base.

In this lesson you will

  • Compare error-handling approaches and their trade-offs
  • Use assertions for programming errors and exceptions or results for expected failures

Key concepts

exceptionsresult typeserror codesassert and contracts

The lesson

Different errors need different tools. Programming mistakes (a broken invariant) should be caught by assertions during development. Expected failures such as a malformed line are often best returned as optional or variant results. Rare, serious failures such as a missing configuration file suit exceptions.

Error codes are common in C libraries and systems code but are easy to ignore; mark such functions [[nodiscard]] so the compiler warns when a result is ignored.

Whatever you choose, be consistent within a module and document it. Mixing styles randomly makes callers unsure what to check.

Step by step

  1. Classify ten error situations in the sensor tool.
  2. Choose a strategy for each and justify it.
  3. Add [[nodiscard]] to functions returning results.
  4. Add assertions for internal invariants.

Practice activity

Write a one-page error-handling policy for your capstone and apply it to the parser and file loader.

Expected result: A policy document and code that follows it consistently.

Check your understanding

  1. What should assertions be used for?

    Show answer

    Detecting programming errors and broken invariants during development.

  2. What does [[nodiscard]] do?

    Show answer

    Makes the compiler warn when a function's return value is ignored.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.