Small refactoring and better exception handling