Python基础学习篇—异常处理机制

时间:2022-12-12 21:09:34
当你的程序中出现异常情况时就需要异常处理。比如当你打开一个不存在的文件时。当你的程序中有一些无效的语句时,Python会提示你有错误存在。
下面是一个拼写错误的例子,print写成了Print。Python是大小写敏感的,因此Python将引发一个错误:
>>> Print 'Hello World'
    File "", line 1
      Print 'Hello World'
                        ^
SyntaxError: invalid syntax


>>> print 'Hello World'
Hello World
1、try...except语句
try...except语句可以用于捕捉并处理错误。通常的语句放在try块中,错误处理语句放在except块中。示例如下:
#!/usr/bin/python
# Filename: try_except.py


import sys


try:
s = raw_input('Enter something --> ')
except EOFError:#处理EOFError类型的异常
print '/nWhy did you do an EOF on me?'
sys.exit() # 退出程序
except:#处理其它的异常
print '/nSome error/exception occurred.'

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语句。如果有一个异常程序没有处理,那么Python将调用默认的处理器处理,并终止程序且给出提示。
2、引发异常
你可以用raise语句来引发一个异常。异常/错误对象必须有一个名字,且它们应是Error或Exception类的子类。
下面是一个引发异常的例子:
#!/usr/bin/python
#文件名: raising.py


class ShortInputException(Exception):
'''你定义的异常类。'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast


try:
s = raw_input('请输入 --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# raise引发一个你定义的异常
except EOFError:
print '/n你输入了一个结束标记EOF'
except ShortInputException, x:#x这个变量被绑定到了错误的实例
print 'ShortInputException: 输入的长度是 %d, /
长度至少应是 %d' % (x.length, x.atleast)
else:
print '没有异常发生.'
运行输出如下:
$ python raising.py
请输入 -->
你输入了一个结束标记EOF


$ python raising.py
请输入 --> --> ab
ShortInputException: 输入的长度是 2, 长度至少应是 3


$ python raising.py
请输入 --> abc
没有异常发生.
3、try...finally语句
当你正在读文件或还未关闭文件时发生了异常该怎么办呢?你应该使用try...finally语句以释放资源。示例如下:
#!/usr/bin/python
# Filename: finally.py


import time


try:
f = file('poem.txt')
while True: # 读文件的一般方法
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异常,我们并没有处理这个异常,那么Python将调用默认的处理器,并终止程序,在程序终止之前,finally块中的语句将执行。