DEV Community

CrabPascal
CrabPascal

Posted on

Exceptions in CrabPascal: try/except/finally (v2.12.0) | Exceções no CrabPascal: try/except/finally (v2.12.0)

Bilingual post · Post bilíngue

Jump to: English · Português


English {#english}

Exceptions in CrabPascal: try/except/finally (v2.12.0)

Delphi developers rely on structured exception handling every day — database timeouts, parse failures, user input validation. Sprint 4 (v2.12.0) made CrabPascal's runtime speak that language: try/except, try/finally, typed handlers, and raise.

Basic pattern

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

Division by zero no longer crashes the interpreter silently — it becomes a catchable Exception, matching Delphi semantics closely enough for teaching and prototyping.

Creating and re-raising

procedure ValidatePositive(N: Integer);
begin
  if N <= 0 then
    raise Exception.Create('Value must be positive');
end;

procedure Outer;
begin
  try
    ValidatePositive(-1);
  except
    on E: Exception do
    begin
      WriteLn('Outer saw: ', E.Message);
      raise;  // re-raise to caller
    end;
  end;
end;
Enter fullscreen mode Exit fullscreen mode

raise; without an argument propagates the last exception — essential for layered libraries that log and rethrow.

finally always runs

var
  S: TStringList;
begin
  S := TStringList.Create;
  try
    S.Add('work');
    raise Exception.Create('oops');
  finally
    WriteLn('Cleanup runs');
    S.Free;
  end;
end;
Enter fullscreen mode Exit fullscreen mode

Even when the except block handles an error, finally executes. CrabPascal tracks this separately from the handler stack so resource leaks are less likely during experiments.

Implementation notes

  • Exception.Create is treated as a class method, not only T* constructors.
  • Typed handlers receive a heap-allocated object with Message, not just a string in Err.
  • C codegen for exceptions remained out of scope in Sprint 4 — run mode first, native binaries later.

Test suite

cargo test --test exceptions
Enter fullscreen mode Exit fullscreen mode

Four integration cases cover generic handlers, typed on E: Exception, finally, and re-raise behavior.

When to use exceptions vs Result types

CrabPascal targets Delphi compatibility, not Rust idioms. That means exceptions for control flow in application code is expected — especially in Horse middleware and CRUD services where Embarcadero code uses the same patterns.

Roadmap context

Sprint 5 moves to string functions; Sprint 9–10 bring run vs build-exe parity so exceptions and strings behave the same in native binaries. v2.12.0 is the milestone where defensive Pascal code from your Delphi days actually runs in CrabPascal without rewriting every error path as integer codes.


Português {#portugus}

Exceções no CrabPascal: try/except/finally (v2.12.0)

Desenvolvedores Delphi dependem de tratamento estruturado de exceções todo dia — timeouts de banco, falhas de parse, validação de entrada. A Sprint 4 (v2.12.0) fez o runtime do CrabPascal falar essa língua: try/except, try/finally, handlers tipados e raise.

Padrão básico

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

Divisão por zero não crasha mais o interpretador em silêncio — vira Exception capturável, alinhada o suficiente à semântica Delphi para ensino e prototipagem.

Criar e relançar

procedure ValidatePositive(N: Integer);
begin
  if N <= 0 then
    raise Exception.Create('Value must be positive');
end;

procedure Outer;
begin
  try
    ValidatePositive(-1);
  except
    on E: Exception do
    begin
      WriteLn('Outer saw: ', E.Message);
      raise;  // re-lança para quem chamou
    end;
  end;
end;
Enter fullscreen mode Exit fullscreen mode

raise; sem argumento propaga a última exceção — essencial para bibliotecas em camadas que registram e relançam.

finally sempre executa

var
  S: TStringList;
begin
  S := TStringList.Create;
  try
    S.Add('work');
    raise Exception.Create('oops');
  finally
    WriteLn('Cleanup runs');
    S.Free;
  end;
end;
Enter fullscreen mode Exit fullscreen mode

Mesmo quando o bloco except trata o erro, o finally executa. O CrabPascal rastreia isso separadamente da pilha de handlers para vazar menos recursos durante experimentos.

Notas de implementação

  • Exception.Create é tratado como método de classe, não só construtores T*.
  • Handlers tipados recebem objeto alocado no heap com Message, não só string em Err.
  • Codegen C para exceções ficou fora de escopo na Sprint 4 — run primeiro, binários nativos depois.

Suite de testes

cargo test --test exceptions
Enter fullscreen mode Exit fullscreen mode

Quatro casos de integração cobrem handlers genéricos, on E: Exception tipado, finally e re-raise.

Quando usar exceções vs códigos de retorno

O CrabPascal mira compatibilidade Delphi, não idioms Rust. Exceções para fluxo de controle em código de aplicação são esperadas — especialmente em middleware Horse e serviços CRUD onde código Embarcadero usa os mesmos padrões.

Contexto do roadmap

A Sprint 5 avança para funções de string; as Sprints 9–10 trazem paridade run vs build-exe para exceções e strings se comportarem igual em binários nativos. A v2.12.0 é o marco em que código Pascal defensivo dos seus dias Delphi roda de fato no CrabPascal sem reescrever cada caminho de erro como códigos inteiros.


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

Top comments (0)