gpt4 book ai didi

c++ - 为什么要按基数抛出派生类捕获?

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:59 26 4
gpt4 key购买 nike

对于下面的代码,结果是“EA Exception Finished”,这意味着虽然我们在派生类中抛出了它,但它被基类捕获了。总是吗?如果是这样,我怎样才能使派生类捕获,从而出现“EB Exception Finished”?

此外,我无法准确理解 throw EB()catch(EA&) 的含义。 catch(EA&) 是否意味着 catch block 获取 EA 对象 的引用?

对不起我的无知。如果你能给我推荐一本书或其他关于异常结构的引用资料,那会很有帮助。

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 block 的顺序以修复该行为:

#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??
^~~~~

关于c++ - 为什么要按基数抛出派生类捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39527963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com