Oct 22, 2022

[C++] throw exception in the handling exception state will lead to std::terminate()

Reference:
What happens if my C++ exception handler itself raises an exception?

Throwing exception in the handling exception state will lead to
std::terminate()

#include <iostream>
using namespace std;

struct Object1 {

  ~Object1() noexcept(false) {
    cout << "Object1 Destructor"
         << "\n";
    throw int(10);
  }
};

struct Object2 {
  ~Object2() noexcept(false) {
    cout << "Object2 Destructor"
         << "\n";
    throw double(10);
  }
};

void test() {
  try {
    try {
      Object1 obj1; // In exception state of obj2 but still throws exception
                    // during destruction, std::terminate called.
      Object2 obj2;
    } catch (int &) {
      cout << "catch int"
           << "\n";
    }
  } catch (double &) {
    cout << "catch double"
         << "\n";
  } catch (int &) {
    cout << "catch int"
         << "\n";
  }
}

int main() {
  //
  //
  test();
}
Print:
Object2 Destructor
Object1 Destructor
libc++abi: terminating with uncaught exception of type int
[1]    18250 abort      ./a.out

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.