Using Try and Finally to Help Prevent Memory Leaks During Dynamic Object Creation in Delphi
Using components in Delphi is child's play as long as your logic is sound. All you need to do is drop components on the form and Delphi takes care of dirtier things like allocating and de-allocating memory for the object. There are times when it doesn't handle memory allocation, however, depending on your needs. This article will explain how to handle those times.
A couple of things should be noted in the above code. Firstly, I have passed the own parameter as nil; setting the Owner to self or Form1 and explicitly freeing it can cause unhappy errors. Every descendant of TComponent can own another component or be owned, which means that the Owner component is responsible for allocation and deallocation of memory of the owned component. In drag-drop situations every component is owned by a Form which itself is owned by the application. This makes memory management easy.
In the case of a component created during runtime, however, the Owner property is determined by the parameter passed in the Constructor method. Creating an object with Form or Self as Owner and then freeing it explicitly can cause another access violation error when the owner component tries to free it, but since the object has been programatically freed it cannot be accessed by the program anymore. So it is always a good idea to create a non-visual component like TTable with the Owner property set to nil if you intend to free it in the block itself.
The second point worth noting is that the TTable constructor has been placed before the "try" block and not within it. As I have stated earlier, statements in the Finally block are executed unconditionally, so if the object creation fails during the call to the construction method, the Free method is called automatically to free resources. However, the Free method in the "finally" block would still try to free memory, but the problem is that the object no longer exists! We would then be facing another access violation error. So it is a better idea to call the constructor method before the try statement and free the object in the Finally block so that the allocated memory is freed anyway.