目录
Python中的异常处理主要通过try/except语句实现。try语句块包含可能会引发异常的代码,而except语句块包含在try块中发生异常时要执行的代码。此外,Python还提供了一个finally语句块,无论try块中的代码是否引发异常,finally块中的代码都会被执行。这可以用来进行一些清理工作,例如关闭文件或释放资源等。
(一)处理异常
#-*- coding:utf-8 -*-
import time
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'
#把所有可能引发错误的语句放在try块中
#在except从句/块中处理所有的错误和异常
(二)引发异常
#创建自己的异常类
class ShortInputException(Exception):#继承Exception类
??? '''A user-defined exception class.'''
??? def __init__(self, length, atleast):? #length是给定输入的长度,atleast则是程序期望的最小长度。
??????? Exception.__init__(self)
??????? self.length = length
??????? self.atleast = atleast
try:
??? s = raw_input('please input str:')
??? if len(s) < 3:
??????? raise ShortInputException(len(s), 3) #用raise引发异常
except EOFError:
??? print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
??? print 'ShortInputException: The input was of length %d, \
?????? # was expecng at least %d' % (x.length, x.atleast)
else
??????????? print 'No exception was raised.'
'''
(三)try..finally
#你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件
try:
??? f = file('1.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
???
?