Tutorial by Examples

Use try-finally to avoid leaking resources (such as memory) in case an exception occurs during execution. The procedure below saves a string in a file and prevents the TStringList from leaking. procedure SaveStringToFile(const aFilename: TFilename; const aString: string); var SL: TStringList; ...
When a function returns an object (as opposed to using one that's passed in by the caller), be careful an exception doesn't cause the object to leak. function MakeStrings: TStrings; begin // Create a new object before entering the try-block. Result := TStringList.Create; try // Execu...
A try-finally block may be nested inside a try-except block. try AcquireResources; try UseResource; finally ReleaseResource; end; except on E: EResourceUsageError do begin HandleResourceErrors; end; end; If an exception occurs inside UseResource, then execution...
A try-except block may be nested inside a try-finally block. AcquireResource; try UseResource1; try UseResource2; except on E: EResourceUsageError do begin HandleResourceErrors; end; end; UseResource3; finally ReleaseResource; end; If an EResourceUsageE...
Object1 := nil; Object2 := nil; try Object1 := TMyObject.Create; Object2 := TMyObject.Create; finally Object1.Free; Object2.Free; end; If you do not initialize the objects with nil outside the try-finally block, if one of them fails to be created an AV will occur on the finally bl...

Page 1 of 1