Python异常的使用

[捕获异常]

try...except :把通常的语句放在try块中 ,而把错误处理语句放在except块中

#! /usr/bin/python # Filename: try_except.py # 2010-7-16 wcdj 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' ######## # output ######## >>> Enter something: Long time no see, guys! Done >>> Enter something: Why did you do an EOF on me? Traceback (most recent call last): File "G:/CrossPlatform/Python 2.5/test.py", line 11, in <module> sys.exit()# exit the program SystemExit >>>

 

 

[引发异常]

我们可以使用raise语句 引发异常,此时还要指明 错误/异常的名称 和伴随异常触发的异常对象 。我们可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类

[注意]
[1] 在这里,我们创建了我们自己的异常类型,其实我们可以使用任何预定义的异常/错误。这个新的异常类型是ShortInputException类。它有两个 ——length是给定输入的长度,atleast则是程序期望的最小长度。
[2] 在except从句中,我们提供了错误类和用来表示错误/异常对象的变量。这与函数调用中的形参和实参概念类似。在这个特别地except从句中,我们使用异常对象的length和atleast域来为用户打印一个恰当的消息。
#! /usr/bin/python # Filename: raise.py # 2010-7-16 wcdj 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.' ######## # output ######## >>> Enter something: How do you do? No exception was raised. >>> Enter something: ab ShortInputException: The input was of length 2,was expecting at least 3 >>> Enter something: Why did you do an EOF on me? >>>

 

 

[try...finally的用法]

假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,这可以使用finally块 来完成。注意,在一个try块下,你可以同时使用except从句和finally块。

[注意]
[1] 有意在每打印一行之前用time.sleep方法 暂停2秒钟。在程序运行的时候,按Ctrl+c 中断/取消程序。
[2] 我们可以观察到KeyboardInterrupt异常 被触发,程序退出。但是,在程序退出之前,finally从句仍然被执行,把文件关闭。

#! /usr/bin/python # Filename: try_finally.py # 2010-7-16 wcdj 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, # note, this comma to ignore new line except EOFError: print '/nWhy did you do an EOF on me?' except: print '/nSome error/exception occurred.' else: print 'No exception was raised.' finally: f.close() print 'Cleaning up...closed the file' ######## # output ######## >>> Programming is fun When the work is done if you wanna make your work also fun use Python ! No exception was raised. Cleaning up...closed the file >>> Programming is fun When the work is done if you wanna make your work also fun Some error/exception occurred. Cleaning up...closed the file >>> # 如果不捕获中断异常的话,即将上述代码的except注释掉,此时按中断,解释器将输出异常的名字: >>> Programming is fun When the work is done Cleaning up...closed the file Traceback (most recent call last): File "G:/CrossPlatform/Python 2.5/test.py", line 14, in <module> print line, # note, this comma to ignore new line File "C:/Python25/lib/idlelib/PyShell.py", line 1246, in write self.shell.write(s, self.tags) File "C:/Python25/lib/idlelib/PyShell.py", line 1235, in write raise KeyboardInterrupt KeyboardInterrupt >>>


你可能感兴趣的:(Python异常的使用)