From d6774a7efcdb670681d6a0d998c413c83fe477a6 Mon Sep 17 00:00:00 2001 From: Dave Abrahams Date: Thu, 21 Aug 2003 14:46:28 +0000 Subject: [PATCH] Add "use virtual inheritance" rule [SVN r19721] --- error_handling.html | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/error_handling.html b/error_handling.html index f1bb7a7..4964af0 100644 --- a/error_handling.html +++ b/error_handling.html @@ -58,12 +58,40 @@

How should I design my exception classes?

    -
  1. Inherit from std::exception. Except in *very* - rare circumstances where you can't afford the cost of a virtual table, +
  2. Derive your exception class + from std::exception. Except in *very* rare + circumstances where you can't afford the cost of a virtual + table, std::exception makes a reasonable exception base class, and when used universally, allows programmers to catch "everything" without resorting to catch(...). For more about - catch(...), see below.
  3. + catch(...), see below. + +
  4. Use virtual inheritance. This insight is due + to Andrew Koenig. Using virtual inheritance from your + exception's base class(es) prevents ambiguity problems at the + catch-site in case someone throws an exception derived from + multiple bases which have a base class in common: + +
    +#include <iostream>
    +struct my_exc1 : std::exception { char const* what() throw(); };
    +struct my_exc2 : std::exception { char const* what() throw(); };
    +struct your_exc3 : my_exc1, my_exc2 {};
    +
    +int main()
    +{
    +   try { throw your_exc3(); }
    +   catch(std::exception const& e) {}
    +   catch(...) { std::cout << "whoops!" << std::endl; }
    +}
    +
    + +The program above prints "whoops" because the +C++ runtime can't resolve which exception instance to +match in the first catch clause. + +
  5. Don't embed a std::string object or any other data