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 = new 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
{
}
}
Exception specification DEPRICATED since C++11
In Java exception specification is a mandatory part of method declaration.
In C++ exception specification is optional. When it is used, the behaviour
is different, than in Java.
class E1;
class E2;
void f() throw(E1)
{
...
throw E1();
...
throw E2();
}
void f()
try {
...
}
catch(E1) { throw; }
catch(...) { std::unexpected(); }
class E1;
class E2;
void f() throw(E1,std::bad_exception)
{
...
throw E1();
...
throw E2();
}
typedef void (*unexpected_handler)();
unexpected_handler set_unexpected(unexpected_handler);
typedef void (*terminate_handler)();
terminate_handler set_terminate(terminate_handler);
void f() throw() { }
Noexcept in C++11
Noexcept operator
bool noexcept(expr);
1. Does not evaluate expr (similar to sizeof)
2. False if
- expr throws
- expr has dynamic_cast
- expr has typeid
- has function which is no noexcept(true) and not constexpr
3. Otherwise true
Noexcept specifier --> since C++11 improved version of trow()
void f() noexcept(expr) { }
void f() noexcept(true) { }
void f() noexcept { }
template <typename T>
void f() noexcept ( noexcept( T::g() ) )
{
g();
}