Examples
Team LiB
Previous Section Next Section

Examples

Example 1: Constructors (invariant error). If a constructor cannot successfully create an object of its type, which is the same as saying that it cannot establish all of the new object's invariants, it should throw an exception. Conversely, an exception thrown from a constructor always means that the object's construction failed and the object's lifetime never began; the language enforces this.

Example 2: Successful recursive tree search. When searching a tree using a recursive algorithm, it can be tempting to return the resultand conveniently unwind the search stackby throwing the result as an exception. But don't do it: An exception means an error, and finding the result is not an error (see [Stroustrup00]). (Note that, of course, failing to find the result is also not an error in the context of the search function; see the find_first_of example in Item 70.)

See also Item 70's examples, replacing "report an error" with "throw an exception."

    Team LiB
    Previous Section Next Section