Improved exception handling.

Should fix #146.