Boost logo

Boost :

From: Daron Anderson (dnanderson_at_[hidden])
Date: 2003-08-23 03:23:49


David Abrahams wrote in message ...
>
>Something I've been meaning to add to more/error_handling.html since
>last fall was just added:
>
> 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.
>

Maybe I am not seeing this from the right perspetive, but wouldn't a better
design guideline be not to use multiple inheritance at all in an exception
hierarchy? I do not see any reason that any exception would have an IS-A
relationship with any two parent classes. I view an exception of being a
very specific error, but multiple inheritance implies that the exception is
simultaneously two types of errors.

As an example, I would personally never derive an exception from both
std::logic_error and std::runtime_error. The exception either occurs as a
runtime error (due to unexcpected runtime behavior) or is an error in the
logic of some developers code (probably happening because some child class
has a bug in it that a base class was guarding against.)

This inability to catch the exception simply underscores why multiple
inheritance is frowned apon in general (aside from an occasional mixin
class.)

Is my thinking on this issue too limited?

Thanks,
Daron Anderson


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk