Skip to content
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