Refactored code and added try catch for exception handling.