问题
I have a problem with the following code. As we can see I have already handled the exception thrown by A's constructor in C's constructor, why should I bother to catch and handle the exception again in the main function?
#include <iostream>
class WException : public std::exception
{
public:
WException( const char* info ) : std::exception(info){}
};
class A
{
public:
A( int a ) : a(a)
{
std::cout << "A's constructor run." << std::endl;
throw WException("A constructor throw exception.");
}
private:
int a;
};
class B
{
public:
B( int b ) : b(b)
{
std::cout << "B's constructor body run." << std::endl;
throw WException("B constructor throw exception");
}
private:
int b;
};
class C : public A, public B
{
public:
C( int a, int b ) try : A(a), B(b)
{
std::cout << "C's constructor run." << std::endl;
}
catch( const WException& e )
{
std::cerr << "In C's constructor" << e.what() << std::endl;
}
};
int main( int argc, char* argv[] )
{
try
{
C c( 10, 100 );
}
catch( const WException& e )
{
std::cerr << "In the main: " << e.what() << std::endl;
}
return 0;
}
回答1:
You cannot actually catch an exception in a constructor. You can handle it, but you have to rethrow it or another exception. The reason is about object integrity and object lifetimes:
If the construction of a
throws, a part of c
has not been initialized and is completely missing - lifetime of a
never starts. a
is not an optional part of C
, otherwise it had to be a pointer or a std::optional
(since C++14 - boost::optional
before that).
So how do you assemble a C
if one of its vital parts cannot be constructed? You can't. c
can never start to exist as a complete object, so there is no way you can exit the constructor normally. That's the reason why if construction of a member object fails, construction of the whole object has to fail, i.e. has to throw an exception.
If you don't throw an exception in C::C
's catch block, the compiler will do so for you.
C++ Standard, §15.3,15:
The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.
For a broader treatment on that topic, see http://www.gotw.ca/gotw/066.htm
来源:https://stackoverflow.com/questions/17564037/c-constructor-initializer-list-throw-exceptions