Protect the clean-up code from exceptions

Fix #2.