对于下面的代码,结果是“EA Exception Finished”,这意味着虽然我们向派生类抛出异常,但它被基类捕获。总是这样吗?如果是这样,我怎样才能让派生类捕获,从而出现“EB Exception Finished”?
我也无法完全理解它是什么意思throw EB()
and catch(EA&)
。并且确实catch(EA&)
表示 catch 块获取 EA 的引用object?
抱歉我的无知。如果您向我推荐一本关于异常结构的书或其他参考资料,那将会有很大的帮助。
class EA {};
class EB: public EA {};
void F()
{
throw EB(); // throw at EB().
}
int main()
{
try
{
F();
}
catch(EA&) // caught here??
{
std::cout<<"EA Exception";
}
catch(EB&) // why not me? every time?
{
std::cout<<"EB Exception";
}
std::cout<<" Finished"<<std::endl;
return 0;
}
改变顺序catch
块来修复该行为:
#include <iostream>
class EA {};
class EB: public EA {};
void F()
{
throw EB(); // throw at EB().
}
int main()
{
try
{
F();
}
catch(EB&) // why not me? every time?
{
std::cout<<"EB Exception";
}
catch(EA&) // caught here??
{
std::cout<<"EA Exception";
}
std::cout<<" Finished"<<std::endl;
return 0;
}
编译器甚至会警告您:
main.cpp:21:3: warning: exception of type 'EB' will be caught
catch(EB&) // why not me? every time?
^~~~~
main.cpp:17:3: warning: by earlier handler for 'EA'
catch(EA&) // caught here??
^~~~~
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)