Finalising the loop and exiting on the right code if something goes wrong