liveBook · Manning

Std::unexpected

As explained in 100 C++ Mistakes and How to Avoid Them

std::unexpected is a deprecated C++ function invoked when an exception violates a dynamic exception specification.

std::unexpected is the runtime response to an exception that violates a dynamic exception specification. Its default behavior calls terminate, which calls abort, turning an incorrect exception guess into an abrupt crash. section 10.8

Dynamic exception specifications create several practical problems:

  • They add runtime checks that match thrown exceptions against the specification and may affect performance. section 10.8
  • A conversion function installed with set_unexpected can replace the failure with a known exception, but may erase useful context across the whole program. section 10.8
  • Removing the specification avoids behavior that differs from ordinary exception propagation and is the recommended modern correction. section 10.8

A hidden specification failure

A std_dev function declares only std::invalid_argument, but arith_mean can throw std::domain_error for empty input. That undeclared exception triggers std::unexpected instead of propagating naturally. Removing the specification lets both errors remain visible to appropriate handlers.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains matching, termination, conversion, performance, and removal, but stops short of implementation internals.
Examples
Uses std_dev, arith_mean, std::domain_error, std::invalid_argument, and a set_unexpected conversion function.
What it assumes
Assumes basic C++ exceptions and catch handling while illustrating specification behavior through a statistical-function example.
What you can do after
Diagnose mismatched dynamic specifications and replace them with ordinary propagation during cautious legacy-code maintenance.
How it connects
Connects dynamic exception specifications with exception propagation, std::terminate, set_unexpected, and exception handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.