Python和java相比,同样拥有强大的异常处理机制,下面让我们一起来看看Python是如何处理异常的
1,try...except....
eg1:
a,b=1,0
try:
a/b
except:
print "ERROR"
print “END”
output:
ERROR
END
解析:try测试里边的代码是否有错,若有错执行except语句,然后执行最后一行print语句,就是说Python的try,except不管怎样都会执行最后的print语句
2,try...except....else.....
eg2:
a,b=1,0
try:
a/2
except:
print "ERROR"
else:
print "执行else"
output:执行else
解析如果try语句没有错误,会执行最后的else语句
3,try...except Exception as e....
eg3:
a,b=1,0
try:
a/b
except Exception as e:
print e
output:integer division or modulo by zero
解析:会打印出具体的异常信息
4,try.....finally....
具体参考此篇博客:http://blog.csdn.net/gamer_gyt/article/details/42439725
5,用raise引发异常,之后的代码将不能执行
用法:raise MyError
eg4:
try:
s = None
if s is None:
print "s 是空对象"
raise NameError #如果引发NameError异常,后面的代码将不能执行
print len(s)
except TypeError:
print "空对象没有长度"
output:
s 是空对象
Traceback (most recent call last):
File "E:\【代码】Python\StudyBasic\SomeProgram\异常.py", line 8, in <module>
raise NameError #如果引发NameError异常,后面的代码将不能执行
NameError
output:
s 是空对象
Traceback (most recent call last):
File "E:\【代码】Python\StudyBasic\SomeProgram\异常.py", line 8, in <module>
raise NameError #如果引发NameError异常,后面的代码将不能执行
NameError
更多用法请参考:http://www.cnblogs.com/dkblog/archive/2011/06/24/2089026.html