typestar

Exceptions in Smalltalk

signal raises; on:do: handles; ensure: always runs.

"Exceptions are messages too: signal raises, on:do: handles."
| result |
result := [10 / 0]
    on: ZeroDivide
    do: [:ex | Transcript show: 'Caught ', ex class name; cr. -1].
Transcript show: 'Answered ', result printString; cr.

[Error signal: 'the chase slipped']
    on: Error
    do: [:ex | Transcript show: 'Press error: ', ex messageText; cr].

"ensure: runs its block no matter how the protected block ends."
[Transcript show: 'printing'; cr]
    ensure: [Transcript show: 'washing up'; cr].

How it works

  1. on: ZeroDivide do: catches by exception class.
  2. The handler block receives the exception and answers a value.
  3. ensure: is the cleanup that runs on every exit.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
481
Tokens
79
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 2 of 3 in Reflection, step 27 of 31 in Language basics.

← Previous Next →

Exceptions in other languages