终止被调用而没有活动异常

时间:2017-09-13 06:54:00

标签: c++ exception

这是我的代码:

#include<iostream>
#include<boost/shared_ptr.hpp>
using namespace std;

void func()
{
    cout<<"   func # "<<endl;
    throw;
}

int main()
{

  try
  {
      int x = -1;
      cout<<"   point 1 "<<endl;
      func();
      cout<<"   point 2 "<<endl;
  }
  catch (exception& e)
  {
      cout<<"  exception caught "<<endl;
      //throw;
  }
  cout<<"   point 3 "<<endl;
  return 0;
}

现在,它给出了这个结果

point 1
func #
terminate called after throwing an instance of in
Abort

但我期待着这个:

point 1
func #
exception caught

我缺少什么?
为什么终止被这样调用?
而且,如果我也从catch块中抛出怎么办?

1 个答案:

答案 0 :(得分:6)

这是因为func有一个空throw语句。如果在没有处理活动异常的情况下执行该语句,则终止假定被调用。

[expr.throw]/4

  

如果当前没有处理异常,则在没有操作数的情况下评估 throw-expression 会调用std :: terminate()。

你需要抛出某些东西才能抓住。一个空的throw语句只有在处理异常时才会抛出。

你可能想写throw std::exception{};

  

而且,如果我也从catch块中抛出怎么办?

假设您应用此修复程序,异常处理程序(throw块)中的空catch将重新抛出您从func内捕获的异常。现在std::terminate将被调用,因为未捕获的异常即将离开main函数。