异常处理机制

来源:互联网 发布:手机应用清除数据 编辑:程序博客网 时间:2024/05/21 12:41

>>> s = input('Enter something --> ') # before you entering something, press Ctrl + D Enter something --> Traceback (most recent call last):  File "<pyshell#2>", line 1, in <module>    s = input('Enter something --> ')EOFError: EOF when reading a line>>> 

看下面这段程序:

#!/usr/bin/env python# Filename: try_except.pyimport sysimport ostry:    s = input('Enter something --> ') # before you entering something,press Ctrl+Dexcept EOFError:    print(os.linesep + 'Why did you do an EOF on me?')    sys.exit() # exit the program# here, we are not exiting the programprint('Well done.')
执行结果1:

>>> ================================ RESTART ================================>>> Enter something --> Why did you do an EOF on me?Traceback (most recent call last):  File "E:/myd/work/Python/try_except.py", line 9, in <module>    sys.exit() # exit the programSystemExit>>> 
执行结果2:

>>> ================================ RESTART ================================>>> Enter something -->  Python is exceptional!Well done.

raise语句:

#!/usr/bin/env python# Filename: raising.pyclass 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: # press Ctrl+D    print('\nWhy did you do an EOF on me?')except ShortInputException as x:    print('ShortInputException: The input was of length %d, \which was expecting at least %d' % (x.length, x.atleast))else:    print('No exception was raised.')
执行结果:

>>> ================================ RESTART ================================>>> Enter something --> Why did you do an EOF on me?>>> ================================ RESTART ================================>>> Enter something --> ShortInputException: The input was of length 0, which was expecting at least 3>>> ================================ RESTART ================================>>> Enter something --> dShortInputException: The input was of length 1, which was expecting at least 3>>> ================================ RESTART ================================>>> Enter something --> PythonNo exception was raised.>>> 

finally语句

#!/usr/bin/env python# Filename: finally.pyimport osimport timeimport sysos.system('cd "E:\myd\work\Python"')poem = ''' Programming is fun When the work is done if you wanna make your work also fun: use Python! '''  f = open('poem.txt', 'w') # open for writing  f.write(poem) # write text to file  f.close()try:    f = open('poem.txt')    while True:        line = f.readline()        if len(line) == 0:            break        time.sleep(2) # here you can press Ctrl+C to raise keyboard interruption        sys.stdout.write(line)finally:    f.close()    print('Cleaning up...closed the file')

输出:

>>> ================================ RESTART ================================>>>  Programming is fun When the work is done if you wanna make your work also fun: use Python! Cleaning up...closed the file>>> ================================ RESTART ================================>>>  Programming is fun When the work is done Cleaning up...closed the fileTraceback (most recent call last):  File "E:/myd/work/Python/finally.py", line 22, in <module>    time.sleep(2) # here you can press Ctrl+C to raise keyboard interruptionKeyboardInterrupt>>> 
呵呵

原创粉丝点击