处理异常

我们可以使用try..except 语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。

try:
    text = input('Enter something --> ')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else:
    print('You entered {0}'.format(text))

我们把所有可能引发错误的语句放在try 块中,然后在except 从句/块中处理所有的错误和异常。except 从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或异常的名称,它会处理所有的错误和异常。

注意:对于每个try 从句,至少都有一个相关联的except 从句。

如果某个错误或异常没有被处理,默认的Python 处理器就会被调用。它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理。

你还可以让try..except 块关联上一个else 从句。当没有异常发生的时候,else 从句将被执行。

我们还可以得到异常对象,从而获取更多有个这个异常的信息。

引发异常

你可以使用raise 语句引发异常。你还得指明错误/异常的名称和伴随异常触发的异常对象。

你可以引发的错误或异常应该分别是一个Error 或Exception 类的直接或间接导出类。

class ShortInputException(Exception):
    '''A user-defined exception class'''
    def __init__(self, length,atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    text = input('Enter something-->')
        if len(text) < 3:
        raise ShortInputException(len(text),3)
        #other work can continue as usual here
except EOFError:
    print('Why did you do an EOF on me')
except ShortInputException as ex:
    print('ShortInputException The input was {0} long, excepted atleast {1}'.format(ex.length,ex.atleast))
else:
    print('No exception was raised.')

Try..Finally

import time

try:
    f = open('poem.txt')
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end = '')
        time.sleep(2) # To make sure it runs for a while
except KeyboardInterrupt:
    print('!! You cancelled the reading from the file.')
finally:
    f.close()
    print('(Cleanig up: closed the file)')

with 语句

在try 块中获得资源,随后又在finally 块中释放资源,这是一种常见的模式。今后,也有一种with 语句能以清晰的方式完成这样的功能。

with open("poem.txt") as f:
    for line in f:
        print(line,end='')

这里的区别就是用with 语句使用open 函数——用with open 就能使得在结束的时候自动关闭文件。