【发布时间】:2013-07-07 23:49:57
【问题描述】:
我对以下代码有疑问。可以看到我已经在C的构造函数中处理了A的构造函数抛出的异常,为什么还要在main函数中再次捕获并处理异常呢?
#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;
}
【问题讨论】:
-
异常是否真的从
C的构造函数中传播出去?如果没有,为什么还要抓住它? -
谁建议你也捕获
main()中的异常?问他这个问题! -
@chris:是的,从统计上讲,我是对的。 ;-)
-
对于它的价值,像构造函数-try-blocks这样的异国语言功能在聚会上可以起到很好的破冰作用。
-
@Nawaz 是的,那些棘手的语言角落之一偶尔会遇到 - 但在阅读了 Sutter 的解释之后,其他任何事情都没有意义;-)
标签: c++ list exception constructor initializer