异常处理:
python在遇到问题时会自动引发异常,也可以用raise故意引发异常,异常种类必须是已有的
>>> raise IOError('This is a test.') Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> raise IOError('This is a test.') OSError: This is a test.
IOError:打不开相应文件
ZeroDivisionError:除以0
SyntaxError:语法错误
捕获异常:
try/expect
def get_age(): while True: try: n = int(input('How old are you?')) return n except ValueError: print('please enter an integer value.')
>>> get_age()
How old are you?a
please enter an integer value.
How old are you?-2
-2
捕获多种异常:把多个异常种类括起来就好了
def convert_to_int1(s,base): try: return int(s,base) except (ValueError, TypeError): return 'error'
>>> convert_to_int1(100,5) 'error' >>> convert_to_int1(5,100) 'error' >>> convert_to_int1('100',5) 25
分别处理不同的异常:用多个except
def convert_to_int2(s,base): try: return int(s,base) except ValueError: return 'value error' except TypeError: return 'type error'
>>> convert_to_int2(100,5) 'type error' >>> convert_to_int2('100',1) 'value error'
捕获所有异常:except后面不加异常类型
def convert_to_int3(s,base): try: return int(s,base) except: return 'error'
>>> convert_to_int3('100',5) 25
清理操作:finally 无论是否引发异常都会执行
def invert(x): try: return 1/x except: return 'error' finally: print('invert(%s) done' %x)
>>> invert(2) invert(2) done 0.5 >>> invert(0) invert(0) done 'error'
with 尽早执行清理操作
下面代码将在for循环后立刻关闭文件
def add_linenum(fname): num = 1 with open(fname,'r') as f: for line in f: print('%04d %s' %(num,line), end ='') num = num+1
>>> add_linenum('story.txt') 0001 Story 0002 0003 Mary had a litte lamb, 0004 and then she had some more.HaHaHa!!