在python中无法cacth nameError

时间:2013-03-24 12:24:50

标签: python python-2.7 nameerror simpy

这是我的代码:

from SimPy.Simulation import *

class Message(Process):
    def arrive(self, destination):
        yield hold, self, 2
        try:
            print "%s %s going to %s" % (now(), self.name, destination.name)
            self.interrupt(destination)
        except NameError, x:
            print "%s is out of reach" % x

我想要做的是打印出目的地在其名称不存在时无法访问,但我仍然遇到通常的python错误:

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    message.arrive(node2)
NameError: name 'node2' is not defined

1 个答案:

答案 0 :(得分:0)

方法中不会出现您的姓名错误。在调用该方法之前发生

Python尝试解析node2,然后才能将node2的值传递给message.arrive()方法。方法代码永远不会执行。

如果你在shell中输入node2,你就会得到同样的错误,你没有定义它,所以Python不知道如何使用它的值。