Exception handling and refactored the code