breaking out of outer loops

Chris Angelico rosuav at gmail.com
Mon Mar 7 18:49:19 EST 2016


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).

ChrisA



More information about the Python-list mailing list