Question: I'm trying to understand the behavior of exceptions in c++.
I wrote the following code:

```
class A{
public: 
    A(){
    };
    ~A(){
        cout<<"hello";

    };
};
int exceptionTest(){

    throw "blablabla";
};

int main(){

        A sd;
    int test = exceptionTest();
     return 0;
}

```

I've noticed that in this case the distructor gets called even though no one caught the exception. 
If I change the "main" code to:

```
 int main(){

            A* sd = new A();
        int test = exceptionTest();
         return 0;
    }

```

The distructor will not be called.
Can anyone please tell me what is the reason for the different behavior?

Thanks,
Li

Answer: 
The fact that you are throwing an exception is irrelevant here. In your first example, `sd` is an object that exists on the stack. When execution exits its scope, for whatever reason, it gets destroyed. In the second example, `sd` is a pointer to an object that was explicitly allocated using `new`. This object will not be destroyed until that pointer is passed to `delete`; since you never do so, your program is currently leaking it.
The standard has the following to say on the matter:

> 
> -9- If no matching handler is found in a program, the function `terminate()` is called; **whether or not the stack is unwound before this call to `terminate()` is implementation-defined**.
> 
> 
> 

So your compiler performs stack unwinding (invoking destructors of locals), others may not. For example, with G++ or codepad.org, this program will **not** output "hello".

---

Dynamically allocated objects are not destroyed until you explicitly destroy them (with **delete** or such). In particular, if an exception occurs in the meantime, code may never reach the deallocation statement.