Refactor to better handle exceptions