Fix exception handling, add tests