refactor to better handle unexpected exceptions