add exception handling in loop