jeudi 25 décembre 2014

Design Pattern for re-trying a code block upon exception

I'm trying to find a design pattern - as I'm sure one exists, this problem is common.


In my application if the user loses their Internet connection, I want to be able to pause the application, allowing the user to check their connection and retry. When a connection is successful the application leaves where it left off.


I've attempted this like so:



while True:
try:
for url in urls:
downloadPage(url)
catch ConnectionException:
raw_input('Connection lost. Press enter to try again')
continue


But this doesn't work, because if the exception is raised within the for loop, it will catch it, but when it continues it will restart from the beginning of the urls list.


I do need to check for connection errors both before the application starts running, and during each request. That way I can pause it. But I don't want to litter all my code with try/catch blocks.


Is there a pattern for this?


Aucun commentaire:

Enregistrer un commentaire