Added exception message and refactored tthe code