Is it possible to have two or more active exceptions at the same time?

C ++ 17 introduces a new function std::uncaught_exceptions:

Detects how many exceptions have been thrown or updated and not yet set to catch their corresponding catch clauses.

The following code:

#include <iostream>

using namespace std;

struct A
{
    ~A()
    {
        cout << std::uncaught_exceptions() << endl;
    }
};

int main()
{
    try
    {
        try
        {

            A a1;
            throw 1;
        }
        catch (...)
        {
            A a2;
            throw;
        }
    }
    catch (...)
    {
        A a3;
    }   
}

outputs:

1

1

0

Is it possible to have two or more active exceptions at the same time?

Is there any example?

+6
source share
1 answer

Yes. Throw an exception from the destructor caused by the stack refusing to handle another exception:

struct D
{
  ~D()
  {
    std::cout << std::uncaught_exceptions() << std::endl;
  }
};

struct E
{
  ~E()
  {
    try
    {
      D d_;
      throw 2;
    }
    catch(...)
    {
      std::cout << std::uncaught_exceptions() << std::endl;
    }
  }
};

int main()
{
  try
  {
    D d;
    E e;
    throw 1;
  }
  catch(...)
  {
  }
}

dThe destructor will be called, and 1is still an active exception. So std::uncaught_exceptions()inside ~dwill be equal to 1.

e , 1 . . a d, . 1, 2 , std::uncaught_exceptions() ~d_ 2.

std::uncaught_exceptions , . , - . , . RAII, , - .

+9

All Articles