beps/docs/proposals/BEP-001-exceptions/legacy-ignore/ideas/scoped-catch-vs-try-catch.md
This document compares BAML's Scoped Catch syntax with the traditional try-catch blocks found in languages like Java, TypeScript, and Python.
In traditional languages, error handling is a wrapper around code. You must indent the "happy path" inside a block.
// TypeScript
function extract(text: string) {
try {
// 1. Indentation level increases
// 2. Scope of variables declared here is limited to the try block
const client = new Client();
return client.run(text);
} catch (e) {
// 3. Handler is at the bottom, far from the start
return fallback();
}
}
In BAML, error handling is a trailer for the scope. You append it at the end, and it applies to the scope above.
// BAML
function Extract(text: string) -> string {
// 1. No indentation change for happy path
client "openai/gpt-4o"
prompt #"Extract from {{ text }}"#
} catch {
// 2. Additive error handling
error => { return fallback() }
}
Scenario: You have a working prototype and want to add error handling.
try { ... }, changing indentation for every line. In git, this looks like you rewrote the whole function.Scenario: You want to access a variable declared in the "try" block after the block ends (if no error occurred).
try are not visible outside. You must declare them before the try block (hoisting).
let result; // Hoisting required
try {
result = complexOperation();
} catch (e) { ... }
use(result);
let result = complexOperation() // No hoisting needed
// If complexOperation throws, we catch it here
} catch { ... }
use(result) // Only reached if no error
try block requires re-indenting.BAML is designed for AI Engineers who often move from "prompt engineering" (prototyping) to "production engineering" (hardening).
| Feature | Traditional Try-Catch | BAML Scoped Catch |
|---|---|---|
| Syntax Type | Wrapper (Block) | Trailer (Block) |
| Indentation | Increases for happy path | Unchanged |
| Variable Scope | Limited to try-block | Function/Scope-wide |
| Diff Size | Large (structural change) | Small (additive change) |
| Placement | Around risky code | End of scope |
| Mental Model | "Attempt this specific part" | "Implicit Try Scope" |