Move the exception handling inside the while loop