try...except
处理异常
在python
中使用 try..except
语句来处理异常。把正常运行的语句放在try
块中,把错误处理语句放在except
块中。
try...except
处理异常用法代码实例:
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
我之前写过一个脚本,就用到了错误处理语句(这是代码的一部分):
try: #try用法
req = urllib2.Request(url,None,req_header)
resp = urllib2.urlopen(req,None,req_timeout)
html = resp.read()
print "Success! >>>",i + 1
print "Rest 10 seconds to continue.",
time.sleep(1)
print ".",
time.sleep(1)
print "."
print "================================"
time.sleep(10)
except : #发现错误,打印
print "We failed to reach a server."
else: #没有错误
print "No exception was raised."
我们可以使用else
输出正常情况下需要运行的内容。
try..finally
语句
读一个文件的时候,无论异常发生与否的情况下都关闭文件可以使
用 finally
语句完成。
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up...closed the file'
以上就是书中处理异常的一些用法。