Python中的异常
当你的程序中出现某些异常的状况的时候,异常就发生了。
一.处理异常
我们可以使用try..except
语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
例如:
#!/usr/bin/python # 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
二.引发异常
你可以使用raise
语句引发异常。你还得指明错误/异常的名称和伴随异常触发的异常对象。你可以引发的错误或异常应该分别是一个Error
或Exception
类的直接或间接导出类。
例如:
#!/usr/bin/python # 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.
三.try..finally
假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally
块来完成。注意,在一个try
块下,你可以同时使用except
从句和finally
块。如果你要同时使用它们的话,需要把一个嵌入另外一个。
#!/usr/bin/python # 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