Fix bug in context managed functions.

These functions previously failed to correctly manage the
context in the face of unexpected exceptions. This is now
fixed.