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从句仍然被执行,把文件关闭。
本文介绍了Python中的异常处理机制,包括try...except语句的基本用法、如何自定义异常类及抛出异常,以及finally子句的应用场景。通过具体示例展示了如何有效地管理和捕获异常,确保程序稳定运行。
1169

被折叠的 条评论
为什么被折叠?



