Constructors
Constructors have no return value. Still, a constructor sometimes must
propagate the failure. There are several method for this: error flags,
like in ios_base, globals, like errno in C, and most importantly exceptions.
However exceptions in constructors have special behaviour.
void f()
{
ifstream inp( "input.dat" );
if ( ! inp ) ...
...
}
class X;
int main()
{
try
{
X *xp = new X();
}
catch( ...) { }
}
class X
{
public:
X(int i) { p = char[i]; init(); }
~X() { delete [] p; }
private:
void init() { ... throw ... }
char *p;
};
Member initialization
class Y
{
public:
Y(int i, int j) : x(i), z(j) { }
private:
X x;
Z z;
};
class Y
{
public:
Y(int i, int j)
try
: x(i), z(j)
{ }
catch( ... )
{
}
private:
X x;
};
#include <iostream>
class X
{
public:
X() { throw 1; }
};
class Y
{
public:
Y()
try
: x()
{ }
catch( ... ) { }
private:
X x;
};
int main()
try {
Y y;
return 0;
}
catch (int i)
{
std::cerr << "exception: " << i << std::endl;
}
Destructors
The rule of thumb for exceptions in destructor: they must never throw.
Desctructor can be called in one of two ways:
-- normal mode
-- call during exception handling
in the later emitting an exception cause undefined behaviour most likely
teh call of terminate()
~X::X() throw()
try
{
...
}
catch( ... ) { ... }
~T::T()
{
if ( ! uncaught_exception() )
{
}
else
{
}
}