简体   繁体   中英

Terminate called without an active exception

This is my code :

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

Now, it's giving this result

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

But I was expecting this:

point 1
func #
exception caught

What am I missing?
Why is terminate being called like this?
And also, what if I also throw from catch block?

This is because func has an empty throw statement. If that statement is executed without an active exception being handled, terminate is supposed to be called.

[expr.throw]/4

If no exception is presently being handled, evaluating a throw-expression with no operand calls std​::​​terminate().

You need to throw something in order to catch. An empty throw statement only has something to throw while an exception is being handled.

You probably meant to write throw std::exception{};

And also, what if I also throw from catch block?

Assuming you apply the fix, the empty throw in the exception handler (the catch block) will re-throw the exception you caught from inside func . And now std::terminate will be called because an uncaught exception is about to leave the main function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM