Updated the code with exception handling