Cleaned up the code and added proper error handling with exceptions