Delphi Memory and Exceptions
Skill53 starsChanged 8 months agoMITView on GitHub
Good memory management practices, memory leak prevention and exception handling in Delphi
In this repository35 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/acbr-patterns.mdCursor rule
- .cursor/rules/delphi-conventions.mdCursor rule
- .cursor/rules/design-patterns.mdCursor rule
- .cursor/rules/dext-patterns.mdCursor rule
- .cursor/rules/dmvc-patterns.mdCursor rule
- .cursor/rules/firebird-patterns.mdCursor rule
- .cursor/rules/horse-patterns.mdCursor rule
- .cursor/rules/intraweb-patterns.mdCursor rule
- .cursor/rules/memory-exceptions.mdCursor rule
- .cursor/rules/mysql-patterns.mdCursor rule
- .cursor/rules/postgresql-patterns.mdCursor rule
- .cursor/rules/refactoring.mdCursor rule
- .cursor/rules/solid-patterns.mdCursor rule
- .cursor/rules/tdd-patterns.mdCursor rule
- .cursor/rules/threading-patterns.mdCursor rule
- acbr-componentsSkill
- Delphi Clean CodeSkill
- Delphi Code ReviewSkill
- Delphi SOLID PatternsSkill
- Design Patterns GoF — DelphiSkill
- DevExpress/DEXT ComponentsSkill
- Dext Framework PatternsSkill
- DelphiMVCFrameworkSkill
- DUnitX Testing PatternsSkill
- Firebird DatabaseSkill
- Horse FrameworkSkill
- Intraweb FrameworkSkill
- MySQL DatabaseSkill
- PostgreSQL DatabaseSkill
- Delphi Code RefactoringSkill
- Delphi Test-Driven Development (TDD) and DUnitXSkill
- Threading & Multi-ThreadingSkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 77
If an API takes a class parameter, declare an interface or instantiate it before the method with try..finally.
- Very specific: line 98
Use try..except primarily to trap recoverable errors, log failures without breaking loops, or transform infrastructure exceptions into more …
- Distinctive: line 99
Never "Swallow" an exception without logical justification.
- Very specific: line 130
Do not use raise Exception.Create(str).
- Very specific: line 144
If you only need to perform a one-off log but want the exception to flow naturally to the global UI, just use pure raise;.
- Distinctive: line 162
When asked to write/refactor code:
- Very specific: line 165
If you generate Services, recommend Dependency Injection via Interfaces (IService) to simplify garbage scanning (GC).
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
🧠 Memory and Exceptions Management in Delphi
Contexto
Delphi has manual memory management for class instances (not derived from interfaces) and uses ARC (Automatic Reference Counting) only for interfaces (IInterface), Strings, Dynamic Arrays and anonymous types. Poor exception handling and forgetting to release memory result in chronic Memory Leaks, catastrophic production failures and systemic instability.
Like AI, you must proactively ensure that every object you create is freed regardless of error streams.
Objectives of this Skill
- Teach how to generate safe blocks of
try..finally. - Prevent Memory Leaks by advising on
FreeandFreeAndNil. - Promote the use of Interfaces for memory automation.
- Institute defensive and typed handling of Exceptions (
try..except). - Introduce custom Domain Exceptions.
🛑 Memory Management: Critical Rules
1. The Gold Standard: try..finally
Whenever an object instance is created and does not have an Owner who manages it, instantiate it in a try..finally block.
try must occur IMMEDIATELY on the line following creation.
var
LList: TStringList;
begin
LList := TStringList.Create;
try
LList.Add('Item 1');
// ...
finally
LList.Free;
end;
end;Anti-Pattern (DO NOT USE):
Code between Create and try may generate an exception, leaking the newly created object.
//WRONG - potential leak!
LList := TStringList.Create;
LList.Add('Item 1');
try
// ...2. Multiple Objects in the Same Block
When allocating multiple temporary resources in the same method, do not nest dozens of try..finally if it is not strictly necessary. But be careful to initialize them all with nil beforehand if there is a chance of leakage, or nest them prudently. The ideal pattern is guaranteed sequential release, but strict nesting is safest for chained allocations:
var
LStream: TMemoryStream;
LReader: TStreamReader;
begin
LStream := TMemoryStream.Create;
try
LReader := TStreamReader.Create(LStream);
try
//logics with both
finally
LReader.Free;
end;
finally
LStream.Free;
end;
end;3. Avoid Creating Objects for Single Passage
If an API takes a class parameter, declare an interface or instantiate it before the method with try..finally. Never pass an inline .Create to a parameter in a method if you do not have an absolute guarantee that the consuming function will free the memory.
4. Garbage Collection via Intefaces
For Dependency Injection, Repository/Service Patterns or Temporary Functional Classes, use inheritance from TInterfacedObject linked to a Interface.
Delphi will kill the instance when the reference counter reaches zero.
var
LService: ICustomerService;
begin
//No try..finally and no .Free calls.
//Memory is scanned when leaving the scope of this procedure.
LService := TCustomerService.Create;
LService.ProcessDailyBatch;
end;🚨 Exception Handling: The Transparent Standard
1. Specific, Not Generic Catches
Use try..except primarily to trap recoverable errors, log failures without breaking loops, or transform infrastructure exceptions into more semantic domain exceptions.
Never "Swallow" an exception without logical justification.
try
PerformDatabaseCommit;
except
//SPECIFIC database capture
on E: EFDDBEngineException do
begin
Logger.Error('Falha no banco de dados [Cód: %d]: %s', [E.ErrorCode, E.Message]);
raise EDatabaseConnectionException.Create('Serviço temporariamente indisponível.');
end;
//Validation SPECIFIC Capture
on E: EValidationException do
begin
ShowWarning(E.Message);
end;
end;Anti-Pattern (DO NOT USE):
This blinds the application trace (hides AccessViolations and Out of Memory).
try
ProcessData;
except
//Wrong! Hides any developer errors during debugging!
end;2. Creating Exceptions Based on Business Logic (DDD)
Do not use raise Exception.Create(str). Declare cohesive exceptions to enable elegant interception by upper layers (REST Controllers, UI Interface).
type
//Domain/Essence of the Rules
EBusinessRuleException = class(Exception);
ECustomerLimitReachedException = class(EBusinessRuleException);
//Infrastructure
EInfrastructureException = class(Exception);
EDatabaseConnectionException = class(EInfrastructureException);3. Encapsulating Errors and Raise without Modifying Context
If you only need to perform a one-off log but want the exception to flow naturally to the global UI, just use pure raise;.
try
SomeDangerousCall;
except
on E: Exception do
begin
Logger.LogError('Critical failure', E);
raise; //REPROJECT the original exception with the same stack-trace
end;
end;💡 AI Action Flow
When asked to write/refactor code:
- Review whether each
TObject.Createwill result in a deallocation (.Freeor Third-Party Ownership). - Inject
try..finallyif you notice legacy code without it. - If you generate Services, recommend Dependency Injection via Interfaces (
IService) to simplify garbage scanning (GC). - In logic that may fail, create Typological Exceptions to validate flow and prevent error code spaghetti conditionals (
if return = -1 then).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

