Consider the following operation:
class C
{
public:
...
virtual void override_me() = 0;
struct AnException : public std::runtime_error {
AnException(const std::string& arg)
: std::runtime_error(arg)
{}
};
void run_some_operation()
{
try {
...
this->override_me();
...
} catch(const std::exception& e) {
throw AnException(e.what()
+ " raised from 'override_me()' "
+ " in 'run_some_operation()'");
}
}
void run_another_operation()
{
try {
...
this->override_me();
...
} catch(const std::exception& e) {
throw AnException(e.what()
+ " raised from 'override_me()' "
+ " in 'run_another_operation()'");
}
}
...
}; // class C
Now, I was doing some Java a few months ago, and I encountered Java's way of
doing this. Each 'Throwable' has another member, a 'Cause'. So above, the
'Cause' of the 'AnException' would be whatever exception 'override_me()' threw.
In Java, of course, you can get a stack trace to the point where the exception
was thrown, so storing a nested exception allows the nested exception's
stacktrae to also be shown. In the above example, the stacktrace for the
'AnException' would be where it is thrown in the 'run_some_operation()'
function, while the stack trace for the exception that triggered that
exception be from wherever it was thrown. (I hope that's not too confusing.)
Now, in C++ exceptions store stack traces up to the point they were thrown
from (it would be nice if they could...) so nesting exceptions like this isn't
too useful. But it still allows a little bit more detail to be stored, and
avoids having to do some text processing (appending the message of one
exception as well as its name to the message of the other one).
I'm thinking of creating a new base class that all my exceptions derive from
that allows this behaviour. Do you guys think it'd be a useful feature to
immitate? Is there anything I'm not thinking of? (I know I'd need to store a
copy of the exception thrown, which I can't do for standard exceptions. But
my own exceptions will all have a 'virtual copy constructor' that I'll use to
get a duplicate of them to store, so that'll be no problem.)
Thanks, please be gentle with the flames if I'm talking cobblers :-)
--
To reply, take of all ZIGs !!