gpt4 book ai didi

c++ - 如果抛出的值匹配多个 catch 子句会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-04 11:55:41 25 4
gpt4 key购买 nike

从字面上看,如果抛出的一个值与多个 catch 子句匹配会发生什么?

编译器决定还是出错?

下面是一个抛出一个值并匹配三个 catch 子句的示例。

我编译它并得到错误。但是不知道那个错误是什么意思...

    #include <iostream>
using namespace std;

class AAA
{
public:
void ShowYou() { cout<<"AAA exception!"<<endl; }
};

class BBB : public AAA
{
public:
void ShowYou() { cout<<"BBB exception!"<<endl; }
};

class CCC : public BBB
{
public:
void ShowYou() { cout<<"CCC exception!"<<endl; }
};

void ExceptionGenerator(int expn)
{
if(expn==1)
throw AAA();
else if(expn==2)
throw BBB();
else
throw CCC();
}

int main(void)
{
try
{
ExceptionGenerator(1);
ExceptionGenerator(1);
ExceptionGenerator(1);
}

catch(AAA& expn)
{
cout<<"catch(AAA& expn)"<<endl;
expn.ShowYou();
}

catch(AAA& expn)
{
cout<<"catch(BBB& expn)"<<endl;
expn.ShowYou();
}

catch(AAA& expn)
{
cout<<"catch(CCC& expn)"<<endl;
expn.ShowYou();
}
system("pause"); return 0;
}

错误 1 ​​error C2312: 'AAA &' : is caught by 'AAA &' on line 40

我得到上面的错误。

这是什么意思?

最佳答案

来自 n3337 标准草案,15.3/4

4 The handlers for a try block are tried in order of appearance. That makes it possible to write handlers that can never be executed, for example by placing a handler for a derived class after a handler for a corresponding base class.

这意味着第二个和第三个catch block 基本上是无法访问的代码。不过,您的程序格式正确,符合规范的编译器不应拒绝它(例如,我的程序只会发出警告)。

当你有一个异常层次结构时,让它们表现出多态性以区分它们:

#include <iostream>
using namespace std;

class AAA {
public:
virtual void ShowYou() { cout<<"AAA exception!"<<endl; }
};

class BBB : public AAA {
public:
void ShowYou() { cout<<"BBB exception!"<<endl; }
};

class CCC : public BBB {
public:
void ShowYou() { cout<<"CCC exception!"<<endl; }
};

void ExceptionGenerator()
{
int expn = 0;
cin >> expn;
if(expn==1)
throw AAA();
else if(expn==2)
throw BBB();
else
throw CCC();
}

int main(void)
{
try
{
ExceptionGenerator();
}
catch(AAA& expn)
{
expn.ShowYou();
}

system("pause"); return 0;
}

关于c++ - 如果抛出的值匹配多个 catch 子句会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16249742/

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