Handling an connection error with Twython

MRAB python at mrabarnett.plus.com
Fri May 24 11:51:26 EDT 2019

On 2019-05-24 09:25, Cecil Westerhof wrote:
> Dennis Lee Bieber <wlfraed at ix.netcom.com> writes:
>> On Fri, 24 May 2019 07:49:23 +0200, Cecil Westerhof <Cecil at decebal.nl>
>> declaimed the following:
>>>I did not do that consciously, because I have to try until it is
>>>successful an I return, or I reached the max tries and re-raise the
>>>exception. With a for loop I could exit the loop and cannot re-raise
>>>the exception.
>> 	Your /success/ branch exits the loop by executing a "return" statement.
>> 	Your /fail/ branch exits the loop by "raise" on the third failure.
>> 	A "for" loop would have the same behavior; you just replace the manual
>> initialization and increment of the loop counter.
>> 	for tries in range(max_try):
>> 		try:
>> 			do something
>> 			return successful
>> 		except stuff:
>> 			if tries+1 == max_try:	#since range is 0..max_try-1
>> 				raise
>> You never "fall off the end" of the loop.
> That is true, but by using a 'while True:' loop it is clear you never
> fall off the end of the loop. I find this much clearer. And when there
> is a bug you get into an endless loop instead of fall of the end.
> Which in my opinion is easier to spot and mend. And endless loop is
> noticed the moment it goes wrong. Falling of the end could go without
> an error and will be spotted much later.
You could print a message or raise an exception after the 'for' loop so 
that if it ever falls off the end of the loop you'll get a nice message 
instead of it just looping forever! :-)

More information about the Python-list mailing list