typestar

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

  1. Lines := TStringList.Create corre primero, y el try abre en la línea siguiente.
  2. Exit('(empty)') sale temprano, y aun así Lines.Free en el finally corre igual.
  3. Las dos llamadas toman caminos distintos por FirstLine y ambas terminan liberando la lista.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 1 de 3 en Excepciones; paso 22 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →