我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
1.处理异常
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '
Why did you do an EOF on me?'
sys.exit() # exit the program
except:
print '
Some error/exception occurred.'
# here, we are not exiting the program
print 'Done'
运行结果
# ./try_except.py enter Enter something --> Done # ./try_except.py ctrl+d Enter something --> Why did you do an EOF on me?
2.如何引发异常
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print '
Why did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d,
was expecting at least %d' % (x.length, x.atleast)
else:
print 'No exception was raised.'
运行结果
[root@host python]# ./raising.py Enter something --> ff ShortInputException: The input was of length 2, was expecting at least 3 [root@host python]# ./raising.py Enter something --> 222 No exception was raised.
这里,我们创建了我们自己的异常类型,其实我们可以使用任何预定义的异常/错误。这个新的异常类型是ShortInputException类。它有两个域——length是给定输入的长度,atleast则是程序期望的最小长度。
3.使用finally
#!/usr/bin/python
# Filename: finally.py
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'
运行结果
# ./finally.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Cleaning up...closed the file
# ./finally.py
Programming is fun
When the work is done
^CCleaning up...closed the file --ctrl+c to break
Traceback (most recent call last):
File "./finally.py", line 10, in <module>
time.sleep(2)
KeyboardInterrupt
在程序运行的时候,按Ctrl-c中断/取消程序。我们可以观察到KeyboardInterrupt异常被触发,程序退出。但是在程序退出之前,finally从句仍然被执行,把文件关闭