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.
> 
> I've noticed that in this case the distructor gets called even though no one caught the exception. 
> 
> 
> 

That's exactly what to expect.

This mechanism is a RAII consequence that makes you "sure" that resources will be freed even if there is an exception. For example :

```
class File
{
   public:
   File( const std::string filename ) : file_handler(file_open( filename )) { } // whatever the implementation

   ~File() { file_close(file_handler); }

   private:
   FileHandler file_handler;
};

void test(){ throw "This is a test"; }

int main()
{
   File file("test.txt");
   test();
   return false;
}

```

You're assured that the file will be closed even with the throw. So if you use RAII to manage your resources.

That's because when the exception is thrown, until it get catch, it goes back in the call stack and if there is no catch the local objects are destroyed the way they would be if we got out of scope.