首页 > 解决方案 > 一个异常可以触发多个 catch 块吗?

问题描述

我想问这个问题的最简单方法是看看“Caught Potato except”是否会被打印出来。

我知道“捕获的蔬菜除外”会被打印出来,但是在那个捕获块之后它会按顺序继续并尝试查看其他捕获块是否也可以工作?

class Vegetable_Except {};

class Potato_Except : public Vegetable_Except{};

int func(int n){
 if(n < 0)
  throw Potato_Except();
 cout << "n: " << n << " ";
 return func(--n);
}


int main(int argc, char ** argv) {
 try{
  func(3);
  func(2);
 }
 catch(Vegetable_Except & e){
  cout << "Caught Vegetable Except" << endl;
 }
catch(Potato_Except & e){
cout << "Caught Potato Except" << endl;
}
 cout << "We survived the vegetables" << endl;
    return 0;
}

代码略微改编自 UMich F2020 EECS280。

标签: c++exceptiontry-catchthrow

解决方案


推荐阅读