Python编程——异常(except)

来源:互联网 发布:感觉身体被掏空 知乎 编辑:程序博客网 时间:2024/06/12 00:03




#-*- coding=utf-8-*-#try..exceptimport systry:s = raw_input('Enter something -->')except EOFError:print '\nWhy did you do an EOF on me?'sys.exit()  # exit the programexcept:print '\nSome error/exception occurred.'# here, we are not exiting the programelse:print 'No error/exception occurred.'print 'Done''''summary:使用try..except语句来处理异常:把通常的语句放在try块中,而把我们的错误处理语句放在except块中1)把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。2)except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或异常的名称,它会处理 所有的 错误和异常。3)每个try从句,都至少有一个相关联的except从句。4)如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理。5)还可以让try..except块关联上一个else从句。当没有异常发生的时候,else从句将被执行。6)我们还可以得到异常对象,从而获取更多有个这个异常的信息。''''''如何创建自己的异常类型和如何引发异常'''#引发异常:#raise语句#1)要指明错误/异常的名称,和伴随异常触发的异常对象#2)可以引发的错误或异常,应该分别是Error或Exception类的一个直接或间接导出类class ShortInputException(Exception):def __init__(self, length, atLeast):Exception.__init__(self)self.length = lengthself.atLeast = atLeasttry:s = raw_input('Enter something -->')if len(s) < 3:raise ShortInputException(len(s), 3)#实例的创建方法,为什么不用调__init__///??except EOFError:print '\nWhy did you do an EOF on me?'except ShortInputException, x: '''提供了错误类和用来表示错误/异常对象的变量使用异常对象x来捕获异常中的信息,如果为自定义异常,那么x就是异常ShortInputException的实例使用“x.属性名”访问异常信息(length和atleast域)'''print 'ShortInputException: The input was of length %d, was expecting at least %d' % (x.length, x.atLeast)else:    print 'No exception was raised.'#finally:#sys.exit()#避免程序直接输入Ctrl+C时爆出KeyboardInterrupt异常#'''###finally无论异常发生与否,都需要执行的语句###'''import timetry:f = file('poem.txt')while True:line = f.readline()if len(line) == 0:breaktime.sleep(2)print line,finally:f.close()print 'Cleaning up...closed the  file.'#'''输出Output:Programming is funWhen the work is doneCleaning up...closed the  file.Traceback (most recent call last):  File "ch13_exception.py", line 81, in <module>    time.sleep(2)KeyboardInterrupt'''



0 0