为什么要用派生类派克 [英] Why throw at derived class catches by base?

查看:247
本文介绍了为什么要用派生类派克的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的代码,结果是EA异常完成,这意味着虽然我们抛出派生类,但它被基类捕获。是吗?如果是这样,我如何使派生类捕获,因此EB异常完成出现?



另外我不能确切地得到它的含义是什么c $ c> throw EB()和 catch(EA&)。而 catch(EA&)意味着catch块获取EA 对象的引用



对不起,我的无知。如果你推荐我一本书或某事来引用异常结构,那将是很好的帮助。

  class EA {}; 
class EB:public EA {};

void F()
{
throw EB(); //抛出EB()。
}

int main()
{
try
{
F();
}
catch(EA&)// catch here?
{
std :: cout<EA Exception;
}
catch(EB&)//为什么不是我?每次?
{
std :: cout<EB Exception;
}

std :: cout<<完成<< std :: endl;

return 0;
}


解决方案

原因:


向上推荐


因此总是在第一次抓到。


For the code below, result is "EA Exception Finished", which means although we threw at derived class it caught by base class. Is it always? And if so, how can I make the derived class catches, thus "EB Exception Finished" appears?

Also I can't exactly get what does it mean by throw EB() and catch(EA&). And does catch(EA&) means the catch block gets a reference for EA object?

Sorry for my ignorance. If you recommend me a book or something to refer about exception structure, that'd be great help.

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;
}

解决方案

Reason:

Upcasting

of derived class to base. and hence always getting stuck on the first catch.

这篇关于为什么要用派生类派克的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆