为什么在这个简单的python程序中发生异常?

时间:2015-11-19 13:52:55

标签: python python-2.7 exception

我写了这个非常简单的Python程序,以了解Exception的工作原理:

def Divide(x,y):
    try:
        print (int(a)/int(b))
    except:
        print "Exception Occured!"

但奇怪的是,每次都会发生异常:

>>> Divide(int(1),int(2))
Exception Occured!
>>> Divide(1,2)
Exception Occured!

虽然不应该发生:

>>> print 1/2
0
>>> print (1/2)
0
>>> print (int(1)/int(2))
0

怎么了?

3 个答案:

答案 0 :(得分:6)

ab未定义 - 函数签名中的参数名称为xy

答案 1 :(得分:2)

def Divide(x,y):
    try:
        print (int(a)/int(b))
    except Exception as e:
        print 'Error: ' + str(e)

尝试以这种方式编写相同的代码。你会明白为什么会这样。

答案 2 :(得分:1)

因为你应该定义一个& b。

它的错误与全局参数有关:

          global name 'a' is not defined
相关问题