[python学习]异常

来源:互联网 发布:国考面试报网络培训班 编辑:程序博客网 时间:2024/06/09 20:06

try except
代码:

#!/usr/bin/python# Filename: raising.py# Python version: 3.4.3class ShortInputException(Exception):    '''A user-defined exception class.'''    def __init__(self, length, atleast):        Exception.__init__(self)        self.length = length        self.atleast = atleasttry:    s = input('Enter something --> ')    if len(s) < 3:        raise ShortInputException(len(s), 3)    # Other work can continue as usual hereexcept 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 --> 2ShortInputException: The input was of length 1,           was expecting at least 3>>> 

try finally
代码:

#!/usr/bin/python# Filename: finally.pyimport timetry:    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')

结果:
在运行过程中按control + c中断程序,会执行finally中代码,关闭文件。

>>> Cleaning up...closed the fileTraceback (most recent call last):  File "/Users/junyu92-mbpr/Desktop/Learn/python/简明教程/finally.py", line 12, in <module>    time.sleep(2)KeyboardInterrupt>>> 
0 0
原创粉丝点击