异常
可能出现异常的状况多种多样,比如当你要读某个文件的时候,而文件并不存在;抑或是在程序运行的时候,不小心把它删除了,这些情况都可能出现异常。
而当程序中有一些无效的语句,Python就会告诉你在语句处存在一个错误。下面举一个例子:
一.语法错误
考虑一个简单的print语句。假如我们把print误拼为Print(注意大写),这样Python会引发 一个语法错误。
Print 'Hello World'
File "<stdin>", line 1
Print 'Hello World'
输出显示存在一个SyntaxError:
Print 'Hello World'
^
SyntaxError: invalid syntax
二.基本异常(Exceptions)
在原文中,作者使用了raw_input代码来读取用户的输入,实际上在python3.X版本中,将raw_input()和input()进行了合并,统一采用input()作为输入函数。
所以如果按照2.X版本的代码s = raw_input('Enter something --> ')
运行程序,则会出现以下错误;
Traceback (most recent call last):
File "C:/Python练习/异常.py", line 1, in <module>
s = raw_input('Enter something --> ')
NameError: name 'raw_input' is not defined
改为input()后的输出为;
Enter something -->
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
s = input('Enter something --> ')
EOFError: EOF when reading a line
我们可以看到,Python引发了一个称为EOFError的错误,这个错误基本上意味着它发现一个不期望的文件尾 (在此处为Ctrl-d表示)接下来,我们将学习如何处理这样的错误。
三.异常的处理
我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处 理语句放在except-块中。
# Filename: try_except.py
import sys
try:
s = 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')
当输入ctrl+D的时候,我们得到这样的输出:
Enter something --> ^D
Why did you do an EOF on me?
它的工作原理很简单,我们把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。 except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有 给出错误或异常的名称,它会处理 所有的 错误和异常。对于每个try从句,至少都有一个相关 联的except从句。
如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序的运行,并 且打印一个消息,我们已经看到了这样的处理。
你还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。
三.异常的创建
# 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 = 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 as x:
print('ShortInputException: The input was of length %d was expecting at least %d' % (x.length, x.atleast))
else:
print('No exception was raised')
输出为;
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
这里,我们创建了我们自己的异常类型,其实我们可以使用任何预定义的异常/错误。这个新 的异常类型是ShortInputException类。它有两个域——length是给定输入的长度,atleast则是程序 期望的最小长度。
在except从句中,我们提供了错误类和用来表示错误/异常对象的变量。这与函数调用中的形参 和实参概念类似。在这个特别的except从句中,我们使用异常对象的length和atleast域来为用户 打印一个恰当的消息。
四.try…finally语句
1.关闭文件
假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally块来完成。注意,在一个try块下,你可以同时使用except从句和finally块。如果你要同时使用它们的话,需要把一个嵌入另外一个。
发生异常关闭的实现:
# Filename: finally.py
import time
try:
f= open('poem.txt')
while True: # our usual file-reading idiom
line= f.readline()
if len(line) == 0:
break
time.sleep(2)
print(line,end=" ")
finally:
f.close()
print('Cleaning up...closed the file')
time.sleep会延迟2秒; 在程序运行时按ctrl-c可以中断/取消程序的运行;
KeyboardInterrupt异常发生程序退出, 在程序退出前finally子句被执行, 文件对象总会被关闭;
2.定义清除(clean-up)操作
try语句还可以定义清除操作,用于无论任何时候都需要被执行的语句。
具体如下:
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!')
Goodbye, world!
Traceback (most recent call last):
File "C:/Python练习/定义清楚操作.py", line 3, in <module>
raise KeyboardInterrupt
KeyboardInterrupt