Refactor and handling exceptions