added exception handling and input validation