Re: Exception classes with throwing copy-constructors
On Sep 9, 2:20 pm, Armen Tsirunyan <lordn3m...@gmail.com> wrote:
Dear all,
I need some help understanding the mchanism (as described in the
standard) of the exceptions.
Let's consider an example
#include <iostream>
//exception class, whose copy constructor throws on second and further
invocations
struct Exc
{
Exc(){}
Exc(Exc const &)
{
static int x = 0;
if(x)
throw 0;
++x;
}
};
int main()
{
try
{
throw Exc();
}
catch(Exc e)
{
std::cout << "Exc\n";
Exc e1(e);
}
catch(int)
{
std::cout << "int\n";
}
}
The questions are:
1. What should the output of this progam be, if defined
AFAICanSee, it will try[1] to say "Exc", but will die through a call
to terminate() upon the construction in "Exc e1(e)" line. (Why: 'cause
first copy ctor call is inside "catch(Exc e)", and second throws).
[1] I used "try" because I have no idea what cout is supposed to do if
terminate() is called, and I think cout is not supposed to flush it's
stuff at each call to << (but '\n' might provoke it to flush). But
given that program terminates unexpectedly, all this is moot, because
he who wants to terminate() either has a bug or should know better
what he wants to do with streams and other un-destroyed objects.
2. What whould the output of this progam be, if defined, if we were to
catch Exc by reference
Looks like it should work (only one copy ctor).
3. What whould the output of this progam be, if defined, if we were to
catch Exc by reference, but Exc's copy-constructor ha\\had changed so
that it ALWAYS throws 0.
I am thinking, same answer as 1.
4. What whould the output of this progam be, if defined, if we were to
catch Exc by value, but Exc's copy-constructor ha\\had changed so that
it ALWAYS throws 0.
Same as 1, but with no attempt at any output (because copy ctor in
catch would throw).
Morals:
1) catch by const ref;
2) do not copy exceptions while in the outermost catch.
Is this the advice you are looking for? ;-)
(2 is the special case of a more general rule: thou shalt make
outermost catch a no-throw zone.)
Goran.