Finished the refactoring part.Added some exception handling