I have an API which internally has some exceptions for error reporting. The basic structure is that it has a root exception object which inherits from std::exception
, then it will throw some subclass of that.
Since catching an exception thrown in one library or thread and catching it in another can lead to undefined behavior (at least Qt complains about it and disallows it in many contexts). I would like to wrap the library calls in functions which will return a status code, and if an exception occurred, a copy of the exception object.
What is the best way to store an exception (with it's polymorphic behavior) for later use? I believe that the c++0x futures API makes use of something like this. So what is the best approach?
The best I can think of is to have a clone()
method in each exception class which will return a pointer to an exception of the same type. But that's not very generic and doesn't deal with standard exceptions at all.
Any thoughts?
EDIT: It seems that c++0x will have a mechanism for this (http://www2.research.att.com/~bs/C++0xFAQ.html#rethrow). It is described as "library magic". Does that mean that is doesn't require any of the language features of c++0x? if not, are there any implementations which are compatible with c++03?
EDIT: Looks like boost has an implementation of exception copying :-).
http://www.boost.org/doc/libs/1_43_0/libs/exception/doc/current_exception.html. I'll keep the question option for any non boost::copy_exception
answers.
EDIT: To address j_random_hacker's concerns about the root cause of the exception being an out of memory error. For this particular library and set of exceptions, this is not the case. All exceptions derived from the root exception object represent different types of parsing errors caused by invalid user input. Memory related exceptions will simply cause a std::bad_alloc
to be thrown which is addressed separately.