Clean exception handling and add tests