Python can't catch overridden NameError

血红的双手。 提交于 2020-01-04 04:26:05

问题


How can you explain this:

This code is supposed to override the NameError and then catch it.

OldNameError = NameError
class NameError(OldNameError):
    pass

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

Does not print "hi". 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"

Gives the output I wanted:

hi

What is the explanation?

Thanks!


回答1:


When you write except NameError, you are saying you want to catch exceptions of the type of whatever NameError refers to at the moment you do the catching. Since you changed what NameError is, you are trying to catch your new class. But the exception that is raised is a "real" NameError, not your overriden one.

You can see this if you modify your except clause:

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

The output is:

False
True

. . . indicating that the raised exception is an OldNameError, not your new NameError.

You cannot change what kind of exception is raised due to an undefined name. You can create something called NameError, but it will never be used unless you use it explicitly yourself (as you did in your second example).



来源:https://stackoverflow.com/questions/21803555/python-cant-catch-overridden-nameerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!