Improved exception handling, added unit test.