exception handling and some code refactoring