python需要处理各种异常,以防程序出现不可控制的错误
一般如果知道是哪种异常,则直接捕捉如下:
try:
floatnum = float(raw_input("Please input a float:"))
intnum = int(floatnum)
print 100/intnum
except ZeroDivisionError:
print "Error:you must input a float num which is large or equal then 1!"
except ValueError:
print "Error:you must input a float num!"
但是有时候并不知道是何种异常,或者你并不知道异常的名字,则可以用如下程序:
timestamp = {'timestamp': 1.0000}
try:
timestamp = content['timestap']
except Exception as e:
print('KeyError: %s' %e)
else:
#do something
finally:
#do something
此时可以捕捉任何异常