python异常处理

来源:互联网 发布:守望先锋性能数据 ping 编辑:程序博客网 时间:2024/06/13 00:31
1、捕获,处理异常
 try:
      a = 1/0
      b = test
except AttributeError as e: 
    print str(e)
except ZerovisitionError as e: 
    print str(e) 
finally:
   print 111


 2、抛异常:
raise AttributeError('属性不存在') 


3、with替代文件操作频繁的开、关
一般麻烦情况:
try:
    f = open('aa.txt','w')
    test = f.read()
except IOError as e:
    print('io:',e)
finally:
    print('close')
    f.close()

with情况不需要关闭,他自己会帮你关闭
try:
    with open('bb.txt','w') as f:
       test = f.read()
except IOError as e:
    print(e)
原创粉丝点击