Exception exceptions

Why is the exception thrown from getA() not found?

 #include<iostream> using namespace std; class Base{ protected: int a; public: Base() { a=34; } Base(int i){ a = i; } virtual ~Base() { if(a<0) throw a; } virtual int getA() { if(a < 0) { throw a;} } }; int main() { try { Base b(-25); cout << endl << b.getA(); } catch (int) { cout << endl << "Illegal initialization"; } } 

EDIT:

I understand that you are talking about expanding a stack.
If I changed Base to the following, I now get the Illegal Initialization debugging error for printing. Why am I no longer calling terminate() ?

 Base() { a=34; } Base(int i){ a = i; if(a<0) throw a;} virtual ~Base() { if(a<0) throw a; } virtual int getA() { return a; } 
+4
source share
2 answers

After the getA() call, the first exception is thrown, the so-called unwinding of the stack is triggered, and the object is destroyed. While the object is destroyed, its destructor throws another exception that leaves the body of the destructor and (since this happens during the unwinding of the stack), this causes terminate() be immediately called by the C ++ runtime and the program terminates .

In the second fragment that you sent, the exception is thrown in the constructor, so the constructor does not end, and the destructor is never called (since destructors are called only for fully constructed objects), so there is no way for terminate() call.

+16
source

terminate() no longer called because you are now throwing an exception in the constructor. Thus, the object is not actually created. Therefore, the destructor is never called.

+2
source

Source: https://habr.com/ru/post/1335989/


All Articles