breaking out of outer loops

Terry Reedy tjreedy at udel.edu
Mon Mar 7 21:54:23 EST 2016


On 3/7/2016 6:49 PM, Chris Angelico wrote:
> On Tue, Mar 8, 2016 at 10:42 AM, Chris Kaynor <ckaynor at zindagigames.com> wrote:
>> And the same rough example, using an exception without a function:
>>
>> for file in files:
>>      try:
>>          for line in file:
>>              section = line.split()
>>              for section in line:
>>                  if sectionCorrupt:
>>                      raise Exception('Section corrupt') # You probably want
>> more details here, for possible manual repair. You could also have a custom
>> exception class for more control.
>>      except Exception as e:
>>          print('Failed to process the file {} with error {}.'.format(file,
>> str(e))) # Probably should also print the entire traceback to aid in
>> repairing errors, especially if they are due to a bug in the code, but this
>> is the rough idea.
>
> Yes, although I would more strongly suggest the custom exception
> class. In fact, the way I'd word it is: Never raise Exception, always
> a subclass. Otherwise it's too easy to accidentally catch something
> elsewhere in the code (a ValueError or TypeError or even
> AttributeError).

I would consider raising and catching StopIteration.

-- 
Terry Jan Reedy




More information about the Python-list mailing list