本文介绍了Python无法捕获重写的NameError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何解释这一点?

该代码应该覆盖NameError然后捕获它.

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"

不打印"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

但是此代码:

OldNameError = NameError
class NameError(OldNameError):
    pass

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

给出我想要的输出:

hi

解释是什么?

谢谢!

推荐答案

编写except NameError时,是说您要捕获进行捕获时NameError所指类型的异常.由于您更改了NameError是什么,因此您正在尝试赶上新课程.但是引发的异常是真实" NameError,而不是您覆盖的异常.

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.

如果修改您的except子句,您会看到以下内容:

You can see this if you modify your except clause:

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

输出为:

False
True

. . .表示引发的异常是OldNameError,而不是新的NameError.

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

您无法更改由于未定义名称而引发的异常类型.您可以创建一个叫做 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).

这篇关于Python无法捕获重写的NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 18:40