Python的异常处理(一)

2016-05-26  本文已影响47人  上发条的树

try...except...

tryExcept.py文件

#!/usr/bin/env Python
# coding=utf-8

while 1:
    print "this is a division program."
    c = raw_input("input 'c' continue,ohterwise logout:")
    if c == 'c':
        a = raw_input("first number:")
        b = raw_input("second number:")
        try:
            print float(a)/float(b)
            print "****************"
        except ZeroDivisionError:
            print "the second number can't be zero!"
            print "****************"
    else:
        break

运行结果:

$ python tryExcept.py
this is a division program.
input 'c' continue,ohterwise logout:c
first number:3
second number:2
1.5
****************
this is a division program.
input 'c' continue,ohterwise logout:d
$ 

如果没有异常发生,except子句在try语句执行后被忽略;
如果try子句中有异常发生,则try中语句被忽略,直接跳到except中执行。except之后也可不带任何异常参数,如果发生任何异常,都会跳到except中执行。

在except中,可以根据异常或者其他需求,进行更多的操作。例如:

#!/usr/bin/env Python
# coding=utf-8

class Calculator(object):
    is_raise = False
    def  calc(self,express):
        try:
            return eval(express)
        except ZeroDivisionError:
            if self.is_raise:
                print "zero can not be division."
            else:
                raise
if __name__ == '__main__':
    c = Calculator()
    print c.calc("8/0")

以上,使用了一个函数eval(),作用是:

>>> eval("2+3")
5
>>> eval("2*3")
6

在except子句中,有一个raise,含义是抛出异常信息,所以当is_raise = False时,异常抛出,如下:

$ python Calculator.py
Traceback (most recent call last):
  File "Calculator.py", line 16, in <module>
    print c.calc("8/0")
  File "Calculator.py", line 8, in calc
    return eval(express)
  File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

当is_raise = True时,

if __name__ == '__main__':
    c = Calculator()
    c.is_raise = True #通过实例变量修改
    print c.calc("8/0")
$ python Calculator.py
zero can not be division.
None

最后None是c.calc("8/0")的返回值。

上一篇 下一篇

猜你喜欢

热点阅读