Refactor exception handling