Python cannot intercept overridden nameError

How can you explain this:

This code should override NameError and then catch it.

OldNameError = NameError
class NameError(OldNameError):
    pass

try:
    ccc
except NameError as e:
    print "hi"

Does not print hello. Instead, the output is:

Traceback (most recent call last):
  File "try.py", line 6, in <module>
    ccc
NameError: name 'ccc' is not defined

But this code:

OldNameError = NameError
class NameError(OldNameError):
    pass

try:
    raise NameError("oo")
except NameError:
    print "hi"

It produces the required result:

hi

What is the explanation?

Thank!

+3
source share
1 answer

When you write except NameError, you say that you want to catch exceptions of the type that is referenced NameErrorat the moment you execute the trap. Since you changed what NameErroryou are trying to catch your new class. But the exception created is “real,” NameErrornot your excessive one.

You can see this if you change the except clause:

try:
    ccc
except Exception as e:
    print isinstance(e, NameError)
    print isinstance(e, OldNameError)

Conclusion:

False
True

., OldNameError, NameError.

, - undefined. , NameError, , ( ).

+3

All Articles