15-150: Principles of Functional Programming

Lecture 13: Exceptions

Exceptions play an important role in the system of static and dynamic checks that make SML a safe language.

Exceptions may cause an evaluation to be interrupted or aborted. (Think of division by 0.)

One simple use of exceptions is to signal that invariants are violated or exceptional boundary cases are encountered.

Exceptions can sometimes also be used in backtracking search procedures or other patterns of control flow where a computation needs to be partially undone. We demonstrated this with an n-Queens implementation. We also showed an implementation of n-Queens based on continuations and another implementation based on options. The code file below contains further variations of these three perspectives.

At the end of lecture, we returned to the problem of searching a tree for an element satisfying a predicate. We first examined that problem in Lecture 12, implemented as a search function that takes both a failure continuation and a success continuation as arguments.
Yet more expressive power can be obtained by also passing a failure continuation to the success continuation. For instance, a calling function can simply change the success continuation to obtain all solutions as opposed to a single solution.  Here is an illustration of that idea in a simple setting, namely finding an even integer in an  int tree.

Key Concepts

Sample Code

Some Notes on Exceptions

Some Notes on the n-Queens Problem

Slides from Lecture