[python] try......except.....finally
try:将有可能导致出现异常的语句放到try块中,如果使用了try语句后,后面的程序必须至少要跟一个except或者finally,否则程序会报错
except:捕获try块中可能出现的异常
finally:不管程序是否有无异常,都会最终执行该语句
for example as below:
1 #-*- coding:utf-8 -*- 2 ''' 3 Created on 2018年7月28日 4 5 @author: anyd 6 ''' 7 def fun(a,b): 8 try: 9 value = a/b 10 print "The result is:",value 11 12 except Exception: 13 print 'The division can not be 0' 14 15 finally: 16 print 'done' 17 18 fun(1,1)
结果如下:这个是正常程序,未触发异常
1 The result is: 1
2 done
下面给一个有异常的如下:
1 #-*- coding:utf-8 -*- 2 ''' 3 Created on 2018年7月28日 4 5 @author: anyd 6 ''' 7 def fun(a,b): 8 try: 9 value = a/b 10 print "The result is:",value 11 12 except Exception: 13 print 'The division can not be 0' 14 15 finally: 16 print 'done' 17 18 fun(1,0)
结果如下:由于给除数赋值为0了,所以程序运行肯定会有问题,这样就会触发except
1 The division can not be 0
2 done
以上通过去捕获异常,大家可以看到python其实上也是运行了成功了,如果不增加异常捕获的话,大家可以看看下面例子,整个python就直接报错了无法运行
1 #-*- coding:utf-8 -*- 2 ''' 3 Created on 2018年7月28日 4 5 @author: anyd 6 ''' 7 def fun(a,b): 8 try: 9 value = a/b 10 print "The result is:",value 11 12 # except Exception: 13 # print 'The division can not be 0' 14 15 finally: 16 print 'done' 17 18 fun(1,0)
输出如下:
1 done 2 Traceback (most recent call last): 3 File "C:\Users\anyd\eclipse-workspace\test.py", line 18, in <module> 4 fun(1,0) 5 File "C:\Users\anyd\eclipse-workspace\test.py", line 9, in fun 6 value = a/b 7 ZeroDivisionError: integer division or modulo by zero