Delphi
Exception Handling
Try/Except/Finally in Delphi.
By EZ4Code Team
exceptiontry-excepttry-finally
Code
try
// Code that may raise
raise EDivByZero.Create('Division by zero');
except
on E: EDivByZero do
ShowMessage('Math error: ' + E.Message);
on E: EFileNotFoundException do
ShowMessage('File not found: ' + E.Message);
else
ShowMessage('Unknown error: ' + Exception(ExceptObject).Message);
end;
// Try/Finally (always runs)
SL := TStringList.Create;
try
SL.LoadFromFile('data.txt');
ProcessFile(SL);
finally
SL.Free; // always freed
end;
// Nested
try
try
RiskyOp;
except
on E: Exception do
begin
Log(E.Message);
raise; // re-raise
end;
end;
finally
Cleanup;
end;Explanation
Use except for handling (catches), finally for cleanup (always runs). on E: ExceptionType filters by class. raise; (with semicolon) re-raises the current exception preserving the stack. ExceptObject returns the current exception in the else branch. Always free objects in finally to avoid leaks.
More Delphi Snippets
Units and Classes
Define units with interface and implementation sections.
VCL Form Basics
Create a form with event handlers in Delphi VCL.
Properties and Events
Define properties and event handlers in Delphi.
Generics
Type-safe containers with generics in Delphi.
Interfaces and Reference Counting
Define interfaces with automatic reference counting.
RTTI (Runtime Type Information)
Inspect types and properties at runtime.