Fix to bug with while structure. Add exception