Refactored code for handling exceptions.