Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion LEARNING_PATH_ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ This branch covers branching, looping, procedure signatures, structured error ha
- **Teaches**: Default parameter values, variadic `args`, `info args`/`info default`, and early `return`.
- **Concept Exercise Idea**: *Lasagna Master* (existing story: `lasagna-master`) — implement recipe helpers with default arguments and variadic `args` for layer lists.

### 10. `error-handling`
### 10. `error-handling` ✅

- **Prerequisites**: `procedures`
- **Teaches**: `error`, `return -code error`, `try`/`on`/`trap`/`finally`, `catch`, `errorCode`, and `errorInfo`.
Expand Down
7 changes: 7 additions & 0 deletions concepts/error-handling/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"authors": [
"glennj"
],
"contributors": [],
"blurb": "Learn how to raise, trap, and clean up after errors in Tcl using error, throw, return -code error, try, and catch."
}
211 changes: 211 additions & 0 deletions concepts/error-handling/about.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
# Error Handling

In Tcl, error handling is built on **return codes** and **return options** rather than separate exception class hierarchies.
Every command evaluation produces a result string and an integer return code (`0` for `ok`, `1` for `error`, `2` for `return`, `3` for `break`, and `4` for `continue`).
Tcl also tracks a dictionary of metadata options, such as `-errorcode` and `-errorinfo` (dictionaries are discussed in a later concept).

## Raising Errors

### `error`

The classic `error` command raises an error with a message, and optionally customizes the stack trace and error code:

```tcl
error message ?info? ?code?
```

```tcl
proc require_non_empty {text} {
# `eq` compares strings (covered in `string-comparison` later)
if {$text eq ""} {
error "input cannot be empty"
}
return $text
}
```

When `code` is omitted, Tcl sets `-errorcode` to `NONE`.

### `throw`

`throw` (introduced in Tcl 8.6) is the idiomatic way to raise structured errors:

```tcl
throw type message
```

`type` is a non-empty list of words representing the error category from most general to most specific, and `message` is the human-readable description:

```tcl
proc withdraw {balance amount} {
if {$amount <= 0} {
throw {BANK INVALID_AMOUNT} "amount must be positive"
}
if {$amount > $balance} {
throw {BANK INSUFFICIENT_FUNDS} "cannot withdraw $amount from $balance"
}
return [expr {$balance - $amount}]
}
```

Notice the argument order difference: `error` takes `message` first (with `code` third), whereas `throw` takes `type` first and `message` second.

### `return -code error`

Inside a procedure, `return -code error` behaves like `error`/`throw` while letting you pass return options directly:

```tcl
proc divide {a b} {
if {$b == 0} {
return -code error -errorcode {ARITH DIVZERO {Divide by zero}} "divide by zero"
}
return [expr {double($a) / $b}]
}
```

## Handling Errors with `try`

`try` is Tcl's structured exception-handling command:

```tcl
try body ?handler ...? ?finally script?
```

Handlers are evaluated in order, and **at most one** handler runs.

### `trap` (Matching `-errorcode` Prefixes)

`trap pattern variableList body` matches when the command raises an error (`code == 1`) and its `-errorcode` list begins with `pattern` as a list prefix:

```tcl
try {
withdraw 50 100
} trap {BANK INSUFFICIENT_FUNDS} {msg opts} {
puts "Declined: $msg"
} trap {BANK} {msg opts} {
puts "Other bank error: $msg"
} trap {} {msg opts} {
puts "Any error: $msg"
}
# => Declined: cannot withdraw 100 from 50
```

Because `trap` matches by **list prefix**:

- `trap {BANK INSUFFICIENT_FUNDS}` matches only `{BANK INSUFFICIENT_FUNDS ...}`.
- `trap {BANK}` matches any error whose `-errorcode` starts with `BANK`.
- `trap {}` matches **any** error (because `{}` is a prefix of every list).

Always order more specific `trap` patterns before broader ones.

### Common Built-in `errorCode` Prefixes

Tcl's own commands set structured `-errorcode` lists that you can match with `trap`:

- `{ARITH DIVZERO ...}` -- division by zero in `expr`.
- `{POSIX ENOENT ...}` -- file or directory does not exist (from `open`, `file`, etc.).
- `{TCL LOOKUP COMMAND ...}` -- unknown command or procedure name.
- `{TCL VALUE NUMBER ...}` -- invalid numeric value.
- `NONE` -- default code when `error` is called without a `code` argument.

```tcl
try {
expr {1 / 0}
} trap {ARITH DIVZERO} {msg} {
puts "Caught math error: $msg"
}
# => Caught math error: divide by zero
```

### `on` (Matching Return Codes)

`on code variableList body` matches any completion with the given return code (`ok`, `error`, `return`, `break`, `continue`, or an integer):

```tcl
try {
divide 10 0
} on ok {result} {
puts "Result: $result"
} on error {msg opts} {
# `dict get` looks up a key in a dictionary (discussed in `dictionaries` later)
puts "Failed ([dict get $opts -errorcode]): $msg"
}
# => Failed (ARITH DIVZERO {Divide by zero}): divide by zero
```

You can share a handler body across multiple clauses using `-` (with `\` continuing the `try` command onto the next line):

```tcl
try {
# ...
} trap {ARITH DIVZERO} - \
trap {BANK INVALID_AMOUNT} {msg} {
puts "Invalid calculation: $msg"
}
```

### `finally` (Guaranteed Cleanup)

The `finally` clause runs after the `try` body and any matching handler, regardless of whether the block succeeded, raised an error, or executed `return`, `break`, or `continue`:

```tcl
proc read_first_line {path} {
# `open`, `gets`, and `close` are file I/O commands (discussed in `channels-and-io` later)
set ch [open $path r]
try {
return [gets $ch]
} finally {
close $ch
}
}
```

Even when the `try` body executes `return`, `finally` runs before the procedure returns to its caller.
If the `finally` body itself raises an error, that new error replaces the original result or error from `try`.

## Handling Errors with `catch`

`catch` is Tcl's lower-level error-trapping primitive:

```tcl
catch script ?resultVar? ?optionsVar?
```

It evaluates `script` and returns the integer return code (`0` when `script` succeeds, `1` on error).
If `resultVar` and `optionsVar` are given, `catch` stores the result (or error message) and return options dictionary in those variables:

```tcl
set code [catch {expr {1 / 0}} result opts]
if {$code != 0} {
puts "Code: $code, ErrorCode: [dict get $opts -errorcode], Message: $result"
}
# => Code: 1, ErrorCode: ARITH DIVZERO {Divide by zero}, Message: divide by zero
```

Use `catch` for short inline checks where you only care whether a command succeeded.
Prefer `try` when you need to match specific `-errorcode` values, separate `ok` from `error`, or guarantee cleanup with `finally`.

## Re-throwing and Propagating Errors

When you inspect an error in a `trap`, `on error`, or `catch` block and decide you cannot handle it, re-throw it using `return -options` so that the original `-errorcode` and `-errorinfo` stack trace are preserved:

```tcl
try {
withdraw 50 0
} trap {BANK} {msg opts} {
# Log, then re-throw preserving original metadata
return -options $opts $msg
}
```

Simply calling `error $msg` inside a handler replaces the original `-errorcode` with `NONE` and starts a new stack trace.

## `errorCode` and `errorInfo` Globals

Whenever an error occurs, Tcl also updates two global variables:

- `::errorCode` -- the `-errorcode` list from the most recent error.
- `::errorInfo` -- the accumulated stack trace string from the most recent error.

Inside a procedure, `errorCode` and `errorInfo` are not automatically in scope unless you declare `global errorCode errorInfo` or use `$::errorCode` / `$::errorInfo` (variable scope and `::` namespaces are discussed in later concepts).
Because global variables are overwritten by any subsequent error, reading `-errorcode` and `-errorinfo` from the `opts` dictionary bound by `try` or `catch` is safer and cleaner.
68 changes: 68 additions & 0 deletions concepts/error-handling/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Error Handling

In Tcl, errors are not special exception objects; they are **return codes** accompanied by an error message and metadata.
Every command returns an integer status code: `0` (`ok`) for normal completion and `1` (`error`) when an error occurs.
When a command returns an error, Tcl unwinds the call stack until a `try` or `catch` handler intercepts it or the script terminates.

## Raising Errors (`error`, `throw`, and `return -code error`)

Tcl provides three main ways to signal an error:

- `error message` raises a generic error with the given message.
- `throw typeWords message` raises an error with a structured error code (space-separated words in braces, such as `{INPUT INVALID_PORT}`) and a human-readable `message`.
- `return -code error -errorcode typeWords message` returns an error directly from a procedure with optional metadata.

```tcl
proc parse_port {value} {
# `string is integer -strict` checks for a whole number (covered in more detail later)
if {![string is integer -strict $value]} {
throw {INPUT INVALID_PORT} "port must be an integer, got: $value"
}
if {$value < 1 || $value > 65535} {
error "port out of range: $value"
}
return $value
}
```

Use `throw` (or `return -code error -errorcode ...`) whenever callers need to distinguish specific error categories programmatically.

## Structured Handling with `try`

The `try` command evaluates a body and dispatches to `trap`, `on`, and `finally` clauses:

```tcl
try {
set port [parse_port "abc"]
} trap {INPUT INVALID_PORT} {msg} {
puts "Bad input: $msg"
} on error {msg} {
puts "Other error: $msg"
} finally {
puts "Done checking port"
}
# => Bad input: port must be an integer, got: abc
# => Done checking port
```

- `trap pattern {msgVar}` matches errors whose `-errorcode` starts with `pattern` (for example, `trap {INPUT}` matches `{INPUT INVALID_PORT}`).
Clauses are checked in order, so place more specific patterns before general ones.
- `on code {msgVar}` matches by return code (`ok`, `error`, `return`, `break`, `continue`, or an integer).
`on error` catches any error regardless of its `-errorcode`.
- `finally body` always runs after `try` (and any matching handler) finishes, whether it succeeded or raised an error.

The variable list `{msgVar}` can also be `{}` if you do not need the message, or `{msgVar optsVar}` to also capture an options dictionary (dictionaries are discussed later).

## Quick Suppression with `catch`

For simple checks, `catch` evaluates a script and returns its numeric return code (`0` for `ok`, `1` for `error`).
It also stores the script's result (or error message) in an optional variable:

```tcl
if {[catch {expr {1 / 0}} result]} {
puts "Failed: $result"
}
# => Failed: divide by zero
```

For multi-branch error handling or cleanup guarantees, prefer `try` over `catch`.
22 changes: 22 additions & 0 deletions concepts/error-handling/links.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[
{
"url": "https://www.tcl-lang.org/man/tcl9.0/TclCmd/try.html",
"description": "Official Tcl 9.0 manual page for the try command, covering trap, on, and finally clauses."
},
{
"url": "https://www.tcl-lang.org/man/tcl9.0/TclCmd/throw.html",
"description": "Official Tcl 9.0 manual page for the throw command."
},
{
"url": "https://www.tcl-lang.org/man/tcl9.0/TclCmd/error.html",
"description": "Official Tcl 9.0 manual page for the error command."
},
{
"url": "https://www.tcl-lang.org/man/tcl9.0/TclCmd/catch.html",
"description": "Official Tcl 9.0 manual page for the catch command."
},
{
"url": "https://www.tcl-lang.org/man/tcl9.0/TclCmd/return.html",
"description": "Official Tcl 9.0 manual page for the return command, including -code, -errorcode, and -options."
}
]
17 changes: 17 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,18 @@
"lists"
],
"status": "wip"
},
{
"slug": "calculator-conundrum",
"name": "Calculator Conundrum",
"uuid": "5a1f97ed-77d4-42ce-9631-8088646ac994",
"concepts": [
"error-handling"
],
"prerequisites": [
"procedures"
],
"status": "wip"
}
],
"practice": [
Expand Down Expand Up @@ -1975,6 +1987,11 @@
"uuid": "e2bc4148-dca5-48e8-a936-63f6d703bb7e",
"slug": "dictionaries",
"name": "Dictionaries"
},
{
"uuid": "e84301ef-e4b3-4197-bc3b-ba7839a426cb",
"slug": "error-handling",
"name": "Error Handling"
}
],
"key_features": [
Expand Down
26 changes: 26 additions & 0 deletions exercises/concept/calculator-conundrum/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Hints

## General

- Review the [try manual page][try] and [throw manual page][throw] for full syntax details.
- Every `trap` and `on` clause in `try` requires a variable list (use `{}` when you do not need the message variable).

## 1. Perform basic calculations and raise structured errors

- Use `switch -- $operation` to dispatch between `"+"`, `"*"`, `"/"`, `""`, and a `default` branch.
- Use `throw {CALCULATOR EMPTY_OPERATION} "..."` or `return -code error -errorcode ...` to signal structured errors.
- Integer division in `expr {$operand1 / $operand2}` automatically raises `{ARITH DIVZERO}` when `$operand2` is `0`.

## 2. Format and handle calculation errors

- Wrap the call to `simpleOperation` in `try { ... }`.
- Chain `trap {ARITH DIVZERO} {} { ... }`, `trap {CALCULATOR EMPTY_OPERATION} {} { ... }`, `trap {CALCULATOR UNSUPPORTED_OPERATION} {} { ... }`, and `on error {msg} { ... }`.
- Format the success string after the `try` block (or inside an `on ok {result}` clause).

## 3. Run a calculation with guaranteed audit logging

- Use `try { return [simpleOperation ...] } finally { $auditProc }`.
- Do not add `trap` or `on error` clauses here so that errors still propagate after `finally` runs.

[try]: https://www.tcl-lang.org/man/tcl9.0/TclCmd/try.html
[throw]: https://www.tcl-lang.org/man/tcl9.0/TclCmd/throw.html
Loading
Loading