refactored code and added custom exceptions