python - Why do GeneratorExit and StopIteration have different base classes? -
i taking @ hierarchy of built-in python exceptions, , noticed stopiteration
, generatorexit
have different base classes:
baseexception +-- systemexit +-- keyboardinterrupt +-- generatorexit +-- exception +-- stopiteration +-- standarderror +-- warning
or in code:
>>> generatorexit.__bases__ (<type 'exceptions.baseexception'>,) >>> stopiteration.__bases__ (<type 'exceptions.exception'>,)
when go specific description of each exception, can read following:
https://docs.python.org/2/library/exceptions.html#exceptions.generatorexit
exception generatorexit
raised when generator‘s close() method called. directly inherits baseexception instead of standarderror since technically not error.
https://docs.python.org/2/library/exceptions.html#exceptions.stopiteration
exception stopiteration
raised iterator‘s next() method signal there no further values. derived exception rather standarderror, since not considered error in normal application.
which not clear me. both similar in sense not notify errors, "event" change flow of code. so, not technically errors, , understand should separated rest of exceptions... why 1 subclass of baseexception
, other 1 subclass of exception
?.
in general considered exception
subclasses errors, , when write blind try: except:
(for instance calling third party code), tried catch exception
, maybe wrong , should catching standarderror
.
it quite common use try: ... except exception: ... blocks.
if generatorexit inherit exception following issue:
def get_next_element(alist): element in alist: try: yield element except baseexception: # except exception pass element in get_next_element([0,1,2,3,4,5,6,7,8,9]): if element == 3: break else: print(element) 0 1 2 exception ignored in: <generator object get_next_element @ 0x7fffed7e8360> runtimeerror: generator ignored generatorexit
this example quite simple imagine in try block more complex operation which, in case of failure, ignore issue (or print message) , next iteration.
if catch generic exception, end preventing user of generator breaking loop without getting runtimeerror.
a better explanation here.
edit: answering here long comment.
i'd rather opposite. generatorexit
should inherit exception
rather baseexception
. when catch exception
want catch everything. baseexception
pep-352 states, exceptions need "excepted" in order allow user escape code otherwise catch them. in way can, example, still ctrl-c running code. generatorexit
falls category in order break loops. interesting conversation on comp.lang.python.
Comments
Post a Comment