Change recurson to iteration and handle more exceptions