adding Exception handling and refactoring