Skip to content
Delphi

Ausnahmebehandlung

Try/Except/Finally in Delphi.

#exception#try-except#try-finally

Code

delphi
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;