DEV Community

CrabPascal
CrabPascal

Posted on

Sprint 4 Review: Exception Handling | Review Sprint 4: tratamento de exceções

Bilingual post · Post bilíngue

Jump to: English · Português


English {#english}

Sprint 4 Review: Exception Handling

Continuing our Mintlify docs tour — Sprint 2 covered System.* namespaces. Sprint 4 is where CrabPascal starts feeling like Delphi under failure.

Delphi developers do not treat exceptions as optional. Database timeouts, parse errors, validation failures — all flow through try/except/finally. Sprint 4 (v2.12.0) made the CrabPascal runtime speak that language.

Deliverables from the review

The Sprint 4 Review documents what closed on 2026-05-26:

Feature Behavior
Exception on heap FMessage field; Exception.Create
try/except Generic handler and on E: Exception do with heap object
try/finally finally always executes
raise / raise; Re-raise via last_exception
Division by zero div with zero divisor → catchable exception

Four test cases in tests/exceptions.rs lock the behavior.

Code you can run today

program ExceptDemo;
uses
  System.SysUtils;

begin
  try
    WriteLn(100 div 0);
  except
    on E: Exception do
      WriteLn('Caught: ', E.Message);
  end;
end.
Enter fullscreen mode Exit fullscreen mode

Re-raising preserves the stack story Delphi developers expect:

procedure Outer;
begin
  try
    ValidateInput;
  except
    on E: Exception do
    begin
      Log(E.Message);
      raise;  // propagate to caller
    end;
  end;
end;
Enter fullscreen mode Exit fullscreen mode

finally runs even when control leaves via exception — critical for freeing handles and closing streams.

Three hard-won lessons

  1. Exception.Create is a class method — not just another T* constructor pattern. The runtime had to treat Exception specially.
  2. Typed handlers need heap objects — a string in Err is not enough; on E: Exception do requires a real instance with .Message.
  3. Codegen C stays out of scope — Sprint 4 targeted the interpreter path. Native exception lowering was explicitly deferred to Sprint 13 (honest failure) and beyond.

That third lesson mattered. Shipping fake C stubs would have masked parity gaps for months.

Testing

cargo test --test exceptions
crab-pascal run tests/fixtures/try_except_simple.pas
Enter fullscreen mode Exit fullscreen mode

Compare with check for static validation before runtime:

crab-pascal check MyUnit.pas
Enter fullscreen mode Exit fullscreen mode

Relationship to later sprints

Sprint 4 made run exception-safe. Sprint 13 (v2.21.0) made build-exe honest: codegen now refuses try/except/finally and raise instead of emitting simulated C. If your project depends on structured exception handling — and most Delphi code does — run is the supported path until real native lowering lands.

Docs pointer

Full ceremony notes: Mintlify Roadmap → Sprint 4 Review · Release: v2.12.0. Next in our series: Sprint 7 and Generics.Collections — the collections layer every REST API needs.


Português {#portugus}

Review Sprint 4: tratamento de exceções

Continuando o tour Mintlify — o Sprint 2 cobriu namespaces System.*. O Sprint 4 é onde o CrabPascal começa a parecer Delphi sob falha.

Desenvolvedores Delphi não tratam exceções como opcionais. Timeouts de banco, erros de parse, validação — tudo passa por try/except/finally. O Sprint 4 (v2.12.0) fez o runtime CrabPascal falar essa língua.

Entregas do review

O Sprint 4 Review documenta o fechamento em 2026-05-26:

Recurso Comportamento
Exception no heap Campo FMessage; Exception.Create
try/except Handler genérico e on E: Exception do com objeto no heap
try/finally finally sempre executa
raise / raise; Re-raise via last_exception
Divisão por zero div com divisor zero → exceção capturável

Quatro casos em tests/exceptions.rs travam o comportamento.

Código que roda hoje

program ExceptDemo;
uses
  System.SysUtils;

begin
  try
    WriteLn(100 div 0);
  except
    on E: Exception do
      WriteLn('Caught: ', E.Message);
  end;
end.
Enter fullscreen mode Exit fullscreen mode

Re-raise preserva a história de stack que Delphi espera:

procedure Outer;
begin
  try
    ValidateInput;
  except
    on E: Exception do
    begin
      Log(E.Message);
      raise;  // propaga ao caller
    end;
  end;
end;
Enter fullscreen mode Exit fullscreen mode

finally executa mesmo quando o controle sai por exceção — crítico para liberar handles e fechar streams.

Três lições difíceis

  1. Exception.Create é class method — não só mais um padrão T*. O runtime precisou tratar Exception de forma especial.
  2. Handlers tipados precisam de objetos no heap — string em Err não basta; on E: Exception do exige instância real com .Message.
  3. Codegen C fora de escopo — Sprint 4 mirou o interpretador. Lowering nativo foi adiado explicitamente ao Sprint 13 (falha honesta) e além.

A terceira lição importou. Emitir stubs C falsos teria mascarado gaps de paridade por meses.

Testes

cargo test --test exceptions
crab-pascal run tests/fixtures/try_except_simple.pas
Enter fullscreen mode Exit fullscreen mode

Compare com check para validação estática antes do runtime:

crab-pascal check MyUnit.pas
Enter fullscreen mode Exit fullscreen mode

Relação com sprints posteriores

O Sprint 4 tornou o run seguro para exceções. O Sprint 13 (v2.21.0) tornou o build-exe honesto: o codegen agora recusa try/except/finally e raise em vez de emitir C simulado. Se seu projeto depende de exception handling estruturado — e a maioria dos códigos Delphi depende — run é o caminho suportado até lowering nativo real.

Apontador de docs

Notas completas: Mintlify Roadmap → Sprint 4 Review · Release: v2.12.0. Próximo na série: Sprint 7 e Generics.Collections — a camada de coleções que toda API REST precisa.


Published on dev.to/@crabpascal · Código em CrabPascal

Top comments (0)