From 65ee8d318b4a4378ecf75f75fe85eeb955f015a6 Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Fri, 4 Dec 2026 15:49:15 -0500 Subject: [PATCH 1/3] Add error-handling concept documentation --- concepts/error-handling/.meta/config.json | 7 + concepts/error-handling/about.md | 211 ++++++++++++++++++++++ concepts/error-handling/introduction.md | 68 +++++++ concepts/error-handling/links.json | 22 +++ config.json | 5 + 5 files changed, 313 insertions(+) create mode 100644 concepts/error-handling/.meta/config.json create mode 100644 concepts/error-handling/about.md create mode 100644 concepts/error-handling/introduction.md create mode 100644 concepts/error-handling/links.json diff --git a/concepts/error-handling/.meta/config.json b/concepts/error-handling/.meta/config.json new file mode 100644 index 00000000..32ae2dde --- /dev/null +++ b/concepts/error-handling/.meta/config.json @@ -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." +} diff --git a/concepts/error-handling/about.md b/concepts/error-handling/about.md new file mode 100644 index 00000000..a8239108 --- /dev/null +++ b/concepts/error-handling/about.md @@ -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. diff --git a/concepts/error-handling/introduction.md b/concepts/error-handling/introduction.md new file mode 100644 index 00000000..3125121e --- /dev/null +++ b/concepts/error-handling/introduction.md @@ -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`. diff --git a/concepts/error-handling/links.json b/concepts/error-handling/links.json new file mode 100644 index 00000000..f0090fa8 --- /dev/null +++ b/concepts/error-handling/links.json @@ -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." + } +] diff --git a/config.json b/config.json index 2e9350dd..d5f684ba 100644 --- a/config.json +++ b/config.json @@ -1975,6 +1975,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": [ From 2ddf05821c086d36c993e0f28341914c81723b5f Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Fri, 4 Dec 2026 15:52:53 -0500 Subject: [PATCH 2/3] Add calculator-conundrum concept exercise --- config.json | 12 ++ .../calculator-conundrum/.docs/hints.md | 26 +++ .../.docs/instructions.md | 58 ++++++ .../.docs/introduction.md | 70 +++++++ .../.docs/introduction.md.tpl | 3 + .../calculator-conundrum/.meta/config.json | 17 ++ .../calculator-conundrum/.meta/design.md | 29 +++ .../calculator-conundrum/.meta/exemplar.tcl | 42 ++++ .../calculator-conundrum.tcl | 25 +++ .../calculator-conundrum.test | 116 +++++++++++ .../calculator-conundrum/testHelpers.tcl | 183 ++++++++++++++++++ 11 files changed, 581 insertions(+) create mode 100644 exercises/concept/calculator-conundrum/.docs/hints.md create mode 100644 exercises/concept/calculator-conundrum/.docs/instructions.md create mode 100644 exercises/concept/calculator-conundrum/.docs/introduction.md create mode 100644 exercises/concept/calculator-conundrum/.docs/introduction.md.tpl create mode 100644 exercises/concept/calculator-conundrum/.meta/config.json create mode 100644 exercises/concept/calculator-conundrum/.meta/design.md create mode 100644 exercises/concept/calculator-conundrum/.meta/exemplar.tcl create mode 100644 exercises/concept/calculator-conundrum/calculator-conundrum.tcl create mode 100644 exercises/concept/calculator-conundrum/calculator-conundrum.test create mode 100644 exercises/concept/calculator-conundrum/testHelpers.tcl diff --git a/config.json b/config.json index d5f684ba..b62297ce 100644 --- a/config.json +++ b/config.json @@ -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": [ diff --git a/exercises/concept/calculator-conundrum/.docs/hints.md b/exercises/concept/calculator-conundrum/.docs/hints.md new file mode 100644 index 00000000..e4aebb34 --- /dev/null +++ b/exercises/concept/calculator-conundrum/.docs/hints.md @@ -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 diff --git a/exercises/concept/calculator-conundrum/.docs/instructions.md b/exercises/concept/calculator-conundrum/.docs/instructions.md new file mode 100644 index 00000000..f8a62a64 --- /dev/null +++ b/exercises/concept/calculator-conundrum/.docs/instructions.md @@ -0,0 +1,58 @@ +# Instructions + +In this exercise, you will build a simple calculator that signals structured errors for invalid operations and handles errors gracefully using `try`, `trap`, `on error`, and `finally`. +No `proc` skeletons are provided in `calculator-conundrum.tcl`, so define each procedure yourself using the exact procedure and parameter names given in each task. + +You have three tasks. + +## 1. Perform basic calculations and raise structured errors + +Implement the `simpleOperation` procedure taking `operand1`, `operand2`, and `operation`: + +- Support `"+"` (addition), `"*"` (multiplication), and `"/"` (integer division). +- If `operation` is the empty string `""`, raise an error with `-errorcode` `{CALCULATOR EMPTY_OPERATION}`. +- If `operation` is anything else, raise an error with `-errorcode` `{CALCULATOR UNSUPPORTED_OPERATION}`. +- Do not catch division by zero inside `simpleOperation`; Tcl's `expr` naturally raises `{ARITH DIVZERO}` for integer division by `0`. + +```tcl +simpleOperation 16 51 "+" +# => 67 + +simpleOperation 10 2 "-" +# raises {CALCULATOR UNSUPPORTED_OPERATION} +``` + +## 2. Format and handle calculation errors + +Implement the `calculate` procedure taking `operand1`, `operand2`, and `operation`. +Call `simpleOperation` inside a `try` block and handle outcomes as follows: + +- On success, return `"$operand1 $operation $operand2 = $result"`. +- On `{ARITH DIVZERO}`, return `"Division by zero is not allowed."`. +- On `{CALCULATOR EMPTY_OPERATION}`, return `"Operation cannot be empty."`. +- On `{CALCULATOR UNSUPPORTED_OPERATION}`, return `"Unsupported operation: $operation."`. +- On any other error, return `"Calculation failed: $msg"` where `$msg` is the error message. + +```tcl +calculate 16 51 "+" +# => 16 + 51 = 67 + +calculate 512 0 "/" +# => Division by zero is not allowed. +``` + +## 3. Run a calculation with guaranteed audit logging + +Implement the `calculateWithAudit` procedure taking `operand1`, `operand2`, `operation`, and `auditProc`. +Call `simpleOperation` inside a `try` block and return its numeric result. +Use a `finally` block to invoke `$auditProc` with no arguments whether `simpleOperation` succeeds or raises an error (allowing any error to propagate to the caller). +In Tcl, writing `$auditProc` as a command invokes the procedure whose name is stored in `auditProc`. + +```tcl +proc record_audit {} { + # records that a calculation ran +} + +calculateWithAudit 6 7 "*" record_audit +# => 42 (and record_audit was called) +``` diff --git a/exercises/concept/calculator-conundrum/.docs/introduction.md b/exercises/concept/calculator-conundrum/.docs/introduction.md new file mode 100644 index 00000000..ffaf0cc2 --- /dev/null +++ b/exercises/concept/calculator-conundrum/.docs/introduction.md @@ -0,0 +1,70 @@ +# Introduction + +## 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`. diff --git a/exercises/concept/calculator-conundrum/.docs/introduction.md.tpl b/exercises/concept/calculator-conundrum/.docs/introduction.md.tpl new file mode 100644 index 00000000..b7ea3aaf --- /dev/null +++ b/exercises/concept/calculator-conundrum/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:error-handling} diff --git a/exercises/concept/calculator-conundrum/.meta/config.json b/exercises/concept/calculator-conundrum/.meta/config.json new file mode 100644 index 00000000..7b2baf5c --- /dev/null +++ b/exercises/concept/calculator-conundrum/.meta/config.json @@ -0,0 +1,17 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "calculator-conundrum.tcl" + ], + "test": [ + "calculator-conundrum.test" + ], + "exemplar": [ + ".meta/exemplar.tcl" + ] + }, + "blurb": "Learn how to raise structured errors and handle them cleanly with try, trap, on error, and finally in Tcl." +} diff --git a/exercises/concept/calculator-conundrum/.meta/design.md b/exercises/concept/calculator-conundrum/.meta/design.md new file mode 100644 index 00000000..bcabbd4a --- /dev/null +++ b/exercises/concept/calculator-conundrum/.meta/design.md @@ -0,0 +1,29 @@ +# Design + +## Goal + +The goal of this exercise is to teach structured error handling in Tcl: signaling errors with `throw` and `-errorcode`, intercepting specific error categories with `try`/`trap`/`on error`, and guaranteeing cleanup with `finally`. + +## Learning objectives + +- Signal structured errors with `throw` (or `return -code error -errorcode ...`) using hierarchical error codes. +- Intercept specific `-errorcode` categories using `try` and `trap` prefix matching (both built-in `{ARITH DIVZERO}` and custom `{CALCULATOR ...}` codes). +- Catch remaining errors using `on error` with a message variable. +- Guarantee finalization logic with `finally` across both normal `return` and error propagation. + +## Out of scope + +- Low-level `catch` usage and `::errorCode`/`::errorInfo` globals (covered in `about.md`). +- Re-throwing errors with `return -options`. +- Inspecting `-errorcode` via `dict get` (`dictionaries` is on a separate branch). +- File channel cleanup (`channels-and-io` is downstream). + +## Concepts + +The Concepts this exercise unlocks are: + +- `error-handling` + +## Prerequisites + +- `procedures` diff --git a/exercises/concept/calculator-conundrum/.meta/exemplar.tcl b/exercises/concept/calculator-conundrum/.meta/exemplar.tcl new file mode 100644 index 00000000..572a6a17 --- /dev/null +++ b/exercises/concept/calculator-conundrum/.meta/exemplar.tcl @@ -0,0 +1,42 @@ +proc simpleOperation {operand1 operand2 operation} { + switch -- $operation { + "+" { + return [expr {$operand1 + $operand2}] + } + "*" { + return [expr {$operand1 * $operand2}] + } + "/" { + return [expr {$operand1 / $operand2}] + } + "" { + throw {CALCULATOR EMPTY_OPERATION} "operation cannot be empty" + } + default { + throw {CALCULATOR UNSUPPORTED_OPERATION} "unsupported operation: $operation" + } + } +} + +proc calculate {operand1 operand2 operation} { + try { + set result [simpleOperation $operand1 $operand2 $operation] + } trap {ARITH DIVZERO} {} { + return "Division by zero is not allowed." + } trap {CALCULATOR EMPTY_OPERATION} {} { + return "Operation cannot be empty." + } trap {CALCULATOR UNSUPPORTED_OPERATION} {} { + return "Unsupported operation: $operation." + } on error {msg} { + return "Calculation failed: $msg" + } + return "$operand1 $operation $operand2 = $result" +} + +proc calculateWithAudit {operand1 operand2 operation auditProc} { + try { + return [simpleOperation $operand1 $operand2 $operation] + } finally { + $auditProc + } +} diff --git a/exercises/concept/calculator-conundrum/calculator-conundrum.tcl b/exercises/concept/calculator-conundrum/calculator-conundrum.tcl new file mode 100644 index 00000000..858247b2 --- /dev/null +++ b/exercises/concept/calculator-conundrum/calculator-conundrum.tcl @@ -0,0 +1,25 @@ +# Define each `proc` for Calculator Conundrum yourself below, keeping the exact +# procedure and parameter names shown. +# +# Use `throw` (or `return -code error -errorcode ...`) to raise structured +# errors, and `try` with `trap`, `on error`, and `finally` to handle them. + +# 1. simpleOperation operand1 operand2 operation +# Performs integer addition ("+"), multiplication ("*"), or division ("/") +# on operand1 and operand2. +# - Raises `{CALCULATOR EMPTY_OPERATION}` when operation is "". +# - Raises `{CALCULATOR UNSUPPORTED_OPERATION}` for any other operation. +# - Division by zero naturally raises `{ARITH DIVZERO}` via `expr`. + +# 2. calculate operand1 operand2 operation +# Calls `simpleOperation` inside a `try` block: +# - On success, returns "$operand1 $operation $operand2 = $result". +# - Traps `{ARITH DIVZERO}` -> "Division by zero is not allowed." +# - Traps `{CALCULATOR EMPTY_OPERATION}` -> "Operation cannot be empty." +# - Traps `{CALCULATOR UNSUPPORTED_OPERATION}` -> "Unsupported operation: $operation." +# - On any other error, returns "Calculation failed: $msg". + +# 3. calculateWithAudit operand1 operand2 operation auditProc +# Calls `simpleOperation $operand1 $operand2 $operation` inside `try` and +# returns its result, while always calling `$auditProc` in a `finally` block +# (whether `simpleOperation` succeeds or raises an error). diff --git a/exercises/concept/calculator-conundrum/calculator-conundrum.test b/exercises/concept/calculator-conundrum/calculator-conundrum.test new file mode 100644 index 00000000..c93334d0 --- /dev/null +++ b/exercises/concept/calculator-conundrum/calculator-conundrum.test @@ -0,0 +1,116 @@ +#!/usr/bin/env tclsh +package require tcltest +namespace import ::tcltest::* +source testHelpers.tcl + +# Uncomment next line to view test durations. +#configure -verbose {body error usec} + +############################################################ +source "calculator-conundrum.tcl" + + +# 1. Perform basic calculations and raise structured errors + +test calculator-conundrum-1.1 "addition" -body { + simpleOperation 16 51 "+" +} -returnCodes ok -result 67 + +test calculator-conundrum-1.2 "multiplication" -body { + simpleOperation 32 6 "*" +} -returnCodes ok -result 192 + +test calculator-conundrum-1.3 "integer division" -body { + simpleOperation 512 4 "/" +} -returnCodes ok -result 128 + +test calculator-conundrum-1.4 "empty operation raises CALCULATOR EMPTY_OPERATION" -body { + try { + simpleOperation 1 2 "" + } trap {CALCULATOR EMPTY_OPERATION} {} { + set status "caught empty" + } +} -returnCodes ok -result "caught empty" + +test calculator-conundrum-1.5 "unsupported operation raises CALCULATOR UNSUPPORTED_OPERATION" -body { + try { + simpleOperation 1 2 "-" + } trap {CALCULATOR UNSUPPORTED_OPERATION} {} { + set status "caught unsupported" + } +} -returnCodes ok -result "caught unsupported" + +test calculator-conundrum-1.6 "division by zero raises ARITH DIVZERO" -body { + try { + simpleOperation 10 0 "/" + } trap {ARITH DIVZERO} {} { + set status "caught divzero" + } +} -returnCodes ok -result "caught divzero" + +test calculator-conundrum-1.7 "integer division truncates remainder" -body { + simpleOperation 7 2 "/" +} -returnCodes ok -result 3 + +# 2. Format and handle calculation errors + +test calculator-conundrum-2.1 "calculate formats addition result" -body { + calculate 16 51 "+" +} -returnCodes ok -result "16 + 51 = 67" + +test calculator-conundrum-2.2 "calculate formats multiplication result" -body { + calculate 32 6 "*" +} -returnCodes ok -result "32 * 6 = 192" + +test calculator-conundrum-2.3 "calculate formats division result" -body { + calculate 512 4 "/" +} -returnCodes ok -result "512 / 4 = 128" + +test calculator-conundrum-2.4 "calculate handles division by zero" -body { + calculate 512 0 "/" +} -returnCodes ok -result "Division by zero is not allowed." + +test calculator-conundrum-2.5 "calculate handles empty operation" -body { + calculate 10 2 "" +} -returnCodes ok -result "Operation cannot be empty." + +test calculator-conundrum-2.6 "calculate handles unsupported operation" -body { + calculate 10 2 "**" +} -returnCodes ok -result "Unsupported operation: **." + +test calculator-conundrum-2.7 "calculate handles other errors with on error" -body { + calculate "abc" 2 "+" +} -returnCodes ok -match glob -result "Calculation failed: *" + +# 3. Run a calculation with guaranteed audit logging + +test calculator-conundrum-3.1 "calculateWithAudit runs auditProc on success" -body { + set ::auditCount 0 + proc recordAudit {} { + incr ::auditCount + } + set res [calculateWithAudit 6 7 "*" recordAudit] + list $res $::auditCount +} -cleanup { + unset -nocomplain ::auditCount + rename recordAudit "" +} -returnCodes ok -result {42 1} + +test calculator-conundrum-3.2 "calculateWithAudit runs auditProc even when an error occurs" -body { + set ::auditCount 0 + proc recordAudit {} { + incr ::auditCount + } + set trapped "" + try { + calculateWithAudit 6 0 "/" recordAudit + } trap {ARITH DIVZERO} {} { + set trapped "divzero" + } + list $trapped $::auditCount +} -cleanup { + unset -nocomplain ::auditCount + rename recordAudit "" +} -returnCodes ok -result {divzero 1} + +cleanupTests diff --git a/exercises/concept/calculator-conundrum/testHelpers.tcl b/exercises/concept/calculator-conundrum/testHelpers.tcl new file mode 100644 index 00000000..f3dcf0f6 --- /dev/null +++ b/exercises/concept/calculator-conundrum/testHelpers.tcl @@ -0,0 +1,183 @@ +############################################################# +# Override some tcltest procs with additional functionality + +# Allow an environment variable to override `skip` +proc skip {args} { + if {!( [info exists ::env(RUN_ALL)] && + [string is boolean -strict $::env(RUN_ALL)] && + $::env(RUN_ALL) + )} { + uplevel 1 [list ::tcltest::skip {*}$args] + } +} + +# Exit non-zero if any tests fail. +# The cleanupTests resets the numTests array, so capture it first. +proc cleanupTests {} { + set failed [expr {$::tcltest::numTests(Failed) > 0}] + uplevel 1 ::tcltest::cleanupTests + if {$failed} then {exit 1} +} + +############################################################# +# Some procs that are handy for Tcl test custom matching. +# ref http://www.tcl-lang.org/man/tcl8.6/TclCmd/tcltest.htm#M20 + +# Copy the needed procs into your test file. Use it like this: +# +# customMatch dictionary dictionaryMatch +# test name "description" -body { +# code that returns a dictionary +# } -match dictionary -result {expected dictionary value here} + + +# Compare two dictionaries for the same keys and same values +proc dictionaryMatch {expected actual} { + if {[dict size $expected] != [dict size $actual]} { + return false + } + dict for {key value} $expected { + if {![dict exists $actual $key]} { + return false + } + set actualValue [dict get $actual $key] + + # if this value is a dict then recurse, + # else just check for string equality + if {[string is list -strict $value] && + [llength $value] > 1 && + [llength $value] % 2 == 0 + } { + set procname [lindex [info level 0] 0] + if {![$procname $value $actualValue]} { + return false + } + } elseif {$actualValue ne $value} { + return false + } + } + return true +} +customMatch dictionary dictionaryMatch + + +# Since Tcl boolean values can be more than just 0/1... +# set a yes; set b true +# expr {$a == $b} ;# => 0 +# expr {$a && $b} ;# => 1 +# expr {!!$a == !!$b} ;# => 1 +# set a off; set b no +# expr {$a == $b} ;# => 0 +# expr {$a && $b} ;# => 0 +# expr {!!$a == !!$b} ;# => 1 +# +proc booleanMatch {expected actual} { + return [expr { + [string is boolean -strict $expected] && + [string is boolean -strict $actual] && + !!$expected == !!$actual + }] +} +customMatch boolean booleanMatch + + +# Compare two ordered lists without comparing the lists themselves +# as strings. +# e.g. +# set first { +# a b c +# } +# set second [list a b c] +# expr {$first eq $second} ;# 0 +# expr {$first == $second} ;# 0 +# orderedListsMatch $first $second ;# true +# +proc orderedListsMatch {expected actual} { + if {[llength $expected] != [llength $actual]} { + return false + } + foreach e $expected a $actual { + if {$e != $a} { + return false + } + } + return true +} +customMatch orderedLists orderedListsMatch + + +# two lists have the same elements, in no particular order +proc unorderedListsMatch {expected actual} { + if {[llength $expected] != [llength $actual]} { + return false + } + foreach elem $expected { + if {[lsearch -exact $actual $elem] == -1} { + return false + } + } + return true +} +customMatch unorderedLists unorderedListsMatch + + +# Compare two ordered lists without comparing the lists themselves +# as strings. Calls itself recursively. +proc listOfListsMatch {expected actual} { + set procname [lindex [info level 0] 0] + if {[llength $expected] != [llength $actual]} { + return false + } + foreach e $expected a $actual { + if {[llength $e] > 1 ? (![$procname $e $a]) : ($e != $a)} { + return false + } + } + return true +} +customMatch listOfLists listOfListsMatch + + +# The expected value is one of a list of values. +proc inListMatch {expectedList actual} { + return [expr {$actual in $expectedList}] +} +customMatch inList inListMatch + + +# Compare numbers: for example 5.0 == 5 +proc numberMatch {expected actual} { + return [expr {$expected == $actual}] +} +customMatch numbers numberMatch + + +# Compare floating point numbers +proc floatMatch {expected actual {epsilon 1e-6}} { + return [expr {abs($expected - $actual) <= $epsilon}] +} +customMatch float floatMatch + + +# Compare floating point numbers +proc closeEnough {expected actual {epsilon 1.1}} { + return [expr {abs($expected - $actual) <= $epsilon}] +} +customMatch approxEqual closeEnough + + +# Compare a list of floating point numbers +proc listOfFloatsMatch {expected actual} { + foreach e $expected a $actual { + if {![floatMatch $e $a]} { + return false + } + } + return true +} + +############################################################# +# Convenience function to set the precision of a real number. +proc roundTo {precision number} { + return [format {%.*f} $precision $number] +} From bfea1c23a05c072f22e5ef17354f1a78c8ebbba4 Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Fri, 4 Dec 2026 15:53:32 -0500 Subject: [PATCH 3/3] Mark error-handling complete in roadmap --- LEARNING_PATH_ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LEARNING_PATH_ROADMAP.md b/LEARNING_PATH_ROADMAP.md index 541f33a4..8642e0ce 100644 --- a/LEARNING_PATH_ROADMAP.md +++ b/LEARNING_PATH_ROADMAP.md @@ -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`.