Generalize methods to use MonadIO class, and bracket exceptions in the computation.

This change cleans up old resources if the computation throws an exception.