moved try/except block inside while loop