Navigation:  Programming Cookbook > Exception Handling >

Catching Exceptions

Previous pageReturn to chapter overviewNext page

Protecting a sequence of Smalltalk statements and catching a class of exception, or classes of exception, that occur while executing that sequence is achieved by wrapping the statement sequence in a block (called the protected block, or try-block), and sending the block a #on:do: message to establish a new exception context. The two arguments to #on:do: are the class of Exception to be caught (but catching multiple exceptions is possible), and a monadic block to handle exceptions which are of that kind.

For example:

ByteArray>>safeAt: index

  "Answer the byte at the specified index in the receiver.

  If the index is out of bounds, answer 0"

  ^[self at: index] on: BoundsError do: [:boundsError | 0]


Try browsing references to #on:do: to see some real examples in the base system.