1、可以使用try..except
语句来处理异常,把通常的语句放在try-块中,而把错误处理语句放在except-块中。
# Filename: try_except.py
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'
输出
$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional!
Done
把所有可能引发错误的语句放在try
块中,然后在except
从句/块中处理所有的错误和异常。except
从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或异常的名称,它会处理 所有的 错误和异常。对于每个try
从句,至少都有一个相关联的except
从句。
如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序的运行,并且打印一个消息,在这个例子中已经看到了这样的处理。
还可以让try..catch
块关联上一个else
从句。当没有异常发生的时候,else
从句将被执行。
2、引发异常
可以使用raise
语句 引发 异常,还得指明错误/异常的名称和伴随异常 触发的 异常对象。可以引发的错误或异常应该分别是一个Error
或Exception
类的直接或间接导出类。
# 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
'\nWhy 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.'
输出
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
3、finally
在一个try
块下,可以同时使用except
从句和finally
块。无论异常发生是否,finally块都会执行。如果要同时使用它们的话,需要把一个嵌入另外一个。
# 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'
输出
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
File "finally.py", line 12, in ?
time.sleep(2)
KeyboardInterrupt
在程序运行的时候,按Ctrl-c中断/取消程序,可以观察到KeyboardInterrupt
异常被触发,程序退出,但是在程序退出之前,finally从句仍然被执行,把文件关闭。