Reputation: 13
for i in range(1,1000):
try:
x = some_crazy_function(my_parm(i))
if x in massive:
raise Exception()
massive.append(x)
x = dict(qnother_crazy_functionsl(x.replace('X','Y')))
x = new_func(x['constant'])[0]
next.append(x)
except:
break
I'm fairly new to python and I ran cross this fragment while maintaining someone else's code
To me that looks like a horrible way to exit a loop. Is it the accepted way to code in python and I'll get used to it or is it as bad as it looks?
Upvotes: 0
Views: 116
Reputation: 402303
In the simplest of cases, a break
would be the best (and simplest) way to break out of a loop:
if x in massive:
break
However, if throwing and catching an exception is more apt for your use case, I would recommend first defining your own user defined Exception class:
class MassiveException(Exception):
pass
Next, you can throw it like this:
if x in massive:
raise MassiveException()
And consequently catch it like this:
except MassiveException:
... # do something here
This is better because it makes your intent clear, and also gets rid of the catch-all except which will swallow other exceptions you really don't want swallowed.
Upvotes: 1