try finally end lazarus / 8-Other ---------------------------------------------------------------------- panjas51 · 2008-02-10 12:24 I've seen many of these Code: [Select]try finally end; what is the purpose and the use of this functions? ---------------------------------------------------------------------- Bart · 2008-02-10 13:15 If an exception occurs in the block between try and finally, then the code between finally and end is executed. This makes it possible to free objects etc. Consider this Code: [Select]procedure Oops1; var x: TSomeObject; begin   x := TSomeObject.Create;   x.DoSomeThing   x.Free; end; Now if x.DoSomeThing throws an exception, then x will never be freed in your program (since the line x.Free will never be executed), leading to memory loss o.a. Whereas in this code Code: [Select]procedure Oops1; var x: TSomeObject; begin   x := TSomeObject.Create;   try     x.DoSomeThing   finally     x.Free;   end; end; Now if x.DoSomeThing throws an exception Lazarus jumps to the finally section and will free the x object. Bart ---------------------------------------------------------------------- panjas51 · 2008-02-10 17:01 understood, Just a last precision... Does the code will pass always thru "finally"? Meaning in your exemple that x.free will be always executed? ---------------------------------------------------------------------- Phil · 2008-02-10 19:45 Quote from: "panjas51"understood, Just a last precision... Does the code will pass always thru "finally"? Meaning in your exemple that x.free will be always executed? Yes, even if you call Exit in the try section, the finally section will still be executed. try/finally and try/except are two of the most important features of Delphi/Free Pascal. Programming without them would be almost impossible. Thanks. -Phil ---------------------------------------------------------------------- panjas51 · 2008-02-11 06:55 Thanks guys, Excellent... But what's the difference between TRY/Finally and TRY/Except So far I understood that the first one is: Do the TRY and in case of error goto Finally, in any case Do the Finally.. For the Try/except? ---------------------------------------------------------------------- Leledumbo · 2008-02-11 11:01 with try..except, you can catch particular exception. Usually combined with try..finally. Ex.: Code: [Select] try   try     a:=TAnObject.Create;     a.DoSomethingThatThrowsException;   except     on e: EOutOfMemory do       WriteLn('Out of memory!');     on e: EAccessViolation do       WriteLn('Access violation!');   end; finally   a.Free; end; So you can define different behavior when different exception occurs. ---------------------------------------------------------------------- panjas51 · 2008-02-11 21:48 excellent and understood; thanks