Python基础--学习笔记1

来源:互联网 发布:百度地图js api 编辑:程序博客网 时间:2024/05/21 09:02

 第八章:异常

1、

注:这里的循环只在没有异常引发的情况下才会退出,而且使用expect Exception,打印更加有用的信息

while True:    try:        x = input('Enter the first number: ')        y = input('Enter the second number: ')        value = x/y        print 'x/y is', value    except Exception,e:        print 'Invalid input:',e        print 'Please try again'    else:        break
 
<span style="color:#ff0000;">Enter the first number: 12Enter the second number: 0Invalid input: integer division or modulo by zeroPlease try againEnter the first number: 12Enter the second number:'hello'Invalid input: unsupported operand type(s) for /: 'int' and 'str'Please try againEnter the first number: kdInvalid input: name 'kd' is not definedPlease try againEnter the first number: 12Enter the second number: Invalid input: unexpected EOF while parsing (<string>, line 0)Please try againEnter the first number: 12Enter the second number: 3x/y is 4</span>

2、Finally子句

它用来在可能的异常后进行清理。它和try子句联合使用:

try:    x = 1/0finally: #发生异常后进行清理    print 'Cleaning up...'    del x

上面的代码中,finally子句肯定会被执行,不管try子句中是否发生异常(在try子句之前初始化x的原因是如果不这样做,由于ZeroDivisionError的存在,x就永远不会被赋值。这样就会导致在finally子句中使用del删除它的时候产生异常,而且这个异常是无法捕捉的)。

运行这段代码,在程序崩溃之前,对于变量x的清理就完成了:

Cleaning up...Traceback (most recent call last):  File "<pyshell#209>", line 2, in <module>    x = 1/0ZeroDivisionError: integer division or modulo by zero


另外,还可以在同一个语句中组合使用try、except、finally和else(或其中3个)

try:1/0except NameError:print 'Unknow variable'else:print "That went well"finally:print "Cleaning up."Cleaning up.Traceback (most recent call last):  File "<pyshell#229>", line 2, in <module>    1/0ZeroDivisionError: integer division or modulo by zero


 

try:12/9except NameError:print 'Unknow variable'else:print "That went well"finally:print "Cleaning up."1That went wellCleaning up.


 

原创粉丝点击