TITLE: strings and exception safe exceptions

(Newsgroups: comp.lang.c++.moderated, 29 Mar 99)

MENZL: Gerhard Menzl
>    class ExceptionClass
>    {
>    public:
>       ExceptionClass (std::string msg) : my_msg (msg) {}
>       virtual void DisplayError ();
> 
>    private
>       std::string my_msg;
>    };


BONNARD: Valentin Bonnard <Bonnard.V@wanadoo.fr>

Efficiency isn't a problem here, but...
This is dangerous: the copy ctor of std::string can throw. 

Exception safety of exceptions is a difficult problem. Here 
are some ideas:

- after the error is detected, before you throw and exception, 
  you may annalyse the error and make up an error message w/o 
  any special considerations (except normal exception safety, 
  of course); any exception thrown at this point (esp. bad_alloc) 
  will ``override'' the exception you wanted to throw

- when constructing the exception object (in throw Ex (args)), 
  the same considerations apply

- when copy constructing the exception object, you may better 
  not let any exception escape, or terminate will be called

When designing an hierarchy of exception classes, I have taken 
time to ensure that this third condition is always met (I have 
defined my own string class just to do that).

Note that std::exception, std::bad_alloc, std::bad_cast, and 
std::bad_typeid all offer this garanty. OTOH, classes for 
error diagnostic (std::logic_error, std::runtime_error, and 
everything derived from them don't seem to garanty that).
