📎 Webclip
How to: Design for exception safety
The page says exception-safe code must let exceptions propagate or be handled without leaving partial objects, leaked memory, or unusable data structures behind. It recommends designing exception policy early, catching only when recovery is complete, and letting exceptions bubble up when lower layers lack context.
Reading notes#
- Keep resource wrapper classes simple and limited to a single resource.
- Prefer smart pointers when managing resources manually.
- Use RAII so allocated memory and released handles are tied to automatic object lifetimes.
- Treat
vector,string,make_shared, andfstreamas examples of types that manage acquisition for you. - Distinguish the three guarantees: no-fail prevents propagation, strong leaves state unchanged on failure, and basic keeps the object usable with no leaks.
- Assume destructors do not throw when reasoning about the strong and basic guarantees.
- In user-defined types, use smart pointers or other RAII wrappers for resources.
- Use a function try block when a derived constructor needs to translate an exception from a base class constructor.
- Do not let exceptions escape from destructors; catch and swallow them if a destructor must run risky code.
