How come StopIteration.__base__ is not BaseException?

Terry Reedy tjreedy at udel.edu
Tue Aug 27 14:51:59 EDT 2013


On 8/27/2013 6:02 AM, Marco Buttu wrote:
> On 08/27/2013 11:22 AM, Steven D'Aprano wrote:
>>
>> What matters is that when you catch "nearly everything", StopIteration is
>> included in the "nearly everything", but SysExit and KeyboardInterrupt
>> should not be. Consider:
>>
>>
>> try:
>>      main()
>> except Exception as e:
>>      print('an unexpected error occurred')
>>      log_unhandled_exception(e)
>>      emergency_shutdown()
>>      sys.exit(1)
>> except (KeyboardInterrupt, SysExit):
>>      # User wants to exit.
>>      clean_exit()
>>      sys.exit(0)
>>
>>
>>
>> Which except clause would you expect an unhandled StopIteration to fall
>> under? The unexpected error clause, or the "user wants to exit cleanly"
>> clause?
>
> Thanks Steven, that was clear for me. I was thinking about a design
> concept: how come doesn't it inherit directly from BaseException like
> GeneratorExit does? But I think I got the answer: because we can iterate
> manually and so it can propagate, and so we want an except Exception
> clause catches it.

Until relatively recently, in 2.5, Exception *was* the base exception 
class and for nearly everything, it still is. "All built-in, 
non-system-exiting exceptions are derived from this class. All 
user-defined exceptions should also be derived from this class." 
BaseException was added just so it would be possible to catch nearly 
everything but a few exceptions. The first two were KeyboardInterrupt 
and SystemExit (in 2.5). GeneratorExit was switched in 2.6, but I forget 
the details of why.

-- 
Terry Jan Reedy




More information about the Python-list mailing list