try..finally for COM Interfaces

Add-in Express™ Support Service
That's what is more important than anything else

try..finally for COM Interfaces
 
Alexander Hars




Posts: 3
Joined: 2006-02-28
Hi,

I am curious about the need to wrap calls to Office COM Objects (for example Outlook._Explorer) in try..finally blocks.

Why is it better to use the following pattern:

procedure someProcedure()
var
explorer: Outlook2000._Explorer;
begin
explorer := OutlookApp.ActiveExplorer;
if explorer <> nil
then
try
//...do something with the explorer
finally
explorer := nil;
end;
end;

What are the drawbacks if I omit the try..finally block and shorten the code as follows:

procedure someProcedure()
var
explorer: Outlook2000._Explorer;
begin

explorer := OutlookApp.ActiveExplorer;
if explorer <> nil
then //...do something with the explorer
end;

The explorer variable refers to an interface. So once I leave the procedure the reference count is decremented and the explorer instance should be released from COM automatically by Delphi - even without explicitly setting explorer :=nil ?

Or does Delphi sometimes forget to decrement the reference count when exiting a procedure (for example in the event of an exception)?

Thank you for feedback,

Alexander





Posted 20 Dec, 2006 09:43:03 Top
Dmitry Kostochko


Add-in Express team


Posts: 2875
Joined: 2004-04-05
Hi Alexander,

The explorer variable refers to an interface. So once I leave the procedure the reference count is decremented and the explorer instance should be released from COM automatically by Delphi - even without explicitly setting explorer :=nil ?

Or does Delphi sometimes forget to decrement the reference count when exiting a procedure (for example in the event of an exception)?


Yes, you are right, Delphi should decrement the reference count for local variables. But I personally have an incurable habit to release all used interfaces myself and I think it is a good habit. So, it's up to you to decide whether to use or not to use the try..finally blocks for local variables.


P.S. Note that we take up your forum requests in the order we receive them.
Besides, it may take us some time to investigate your issue. Please be sure we will let you know as soon as the best possible solution is found.
Posted 21 Dec, 2006 07:44:31 Top