if loop replaced by try and catch