try-finally en Delphi
Un TStringList creado antes del try y liberado en el finally, salga la función por donde salga.
program TryFinally;
uses SysUtils, Classes;
// finally runs on every way out: the end, an Exit, or an exception.
function FirstLine(const Text: string): string;
var Lines: TStringList;
begin
Lines := TStringList.Create;
try
Lines.Text := Text;
if Lines.Count = 0 then
Exit('(empty)'); // the early exit still passes through finally
Result := Lines[0];
finally
Lines.Free; // one place holds the cleanup
end;
end;
begin
WriteLn(FirstLine('roasted' + sLineBreak + 'ground' + sLineBreak));
WriteLn(FirstLine(''));
end.
Cómo funciona
Lines := TStringList.Createcorre primero, y eltryabre en la línea siguiente.Exit('(empty)')sale temprano, y aun asíLines.Freeen elfinallycorre igual.- Las dos llamadas toman caminos distintos por
FirstLiney ambas terminan liberando la lista.
Palabras clave y builtins usados aquí
ExitResultWriteLnbeginconstendfinallyfunctionifprogramstringthentryusesvar
El intento, en números
- Líneas
- 20
- Caracteres a escribir
- 524
- Tokens
- 102
- Ritmo de tres estrellas
- 75 tpm
Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 82 segundos.
Paso 1 de 3 en Excepciones; paso 22 de 27 en Fundamentos del lenguaje.