How exactly is your dataset structured?
I have uploaded a small snippet here 55 which is not directly related to your problem but should show how to use StopIteration inside an iterable (in this case the dataloaders are simply reset if running out of bounds).