Python异常处理,,我们可以使用try.
Python异常处理,,我们可以使用try.
我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
1.处理异常
#!/usr/bin/python# Filename: try_except.pyimport 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 programprint ‘Done‘
运行结果
# ./try_except.py enterEnter something -->Done# ./try_except.py ctrl+dEnter something -->Why did you do an EOF on me?
2.如何引发异常
#!/usr/bin/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 = raw_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, x: print ‘ShortInputException: The input was of length %d, was expecting at least %d‘ % (x.length, x.atleast)else: print ‘No exception was raised.‘
运行结果
[root@host python]# ./raising.pyEnter something --> ffShortInputException: The input was of length 2, was expecting at least 3[root@host python]# ./raising.pyEnter something --> 222No exception was raised.
这里,我们创建了我们自己的异常类型,其实我们可以使用任何预定义的异常/错误。这个新的异常类型是ShortInputException类。它有两个域——length是给定输入的长度,atleast则是程序期望的最小长度。
3.使用finally
#!/usr/bin/python# Filename: finally.pyimport timetry: 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‘
运行结果
# ./finally.pyProgramming is funWhen the work is doneif you wanna make your work also fun:use Python!Cleaning up...closed the file# ./finally.pyProgramming is funWhen the work is done^CCleaning up...closed the file --ctrl+c to breakTraceback (most recent call last): File "./finally.py", line 10, in <module> time.sleep(2)KeyboardInterrupt
在程序运行的时候,按Ctrl-c中断/取消程序。我们可以观察到KeyboardInterrupt异常被触发,程序退出。但是在程序退出之前,finally从句仍然被执行,把文件关闭
Python异常处理
相关内容
- 暂无相关文章
评论关闭