异常处理

# -*- coding: utf-8 -*-
'''
except Exception 是捕获所有类型的错误


没有出错的时候会执行else 中的逻辑
finally 里边的语句一定会执行
try:
    code

 except error:
     code
else:
      code
finally:
    code
    
    

主动抛出异常使用raise 关键字
raise Exception("Error")


自定义异常类型步骤:
    1.创建一个类
    2.集成Exception
    3.重写__init__  方法
'''
from _ast import Try

data={}
index = [1,2,3]

try:
#     data['name']
#     index[3]
    pass
except KeyError as e :
    print("没有这个key: ", e)
except Exception as e:
    print("未知错误: ", e)
#没有异常的时候执行的代码
else:
    print("一切正常")
    
    #一定会执行的代码
finally:
    print("一定会执行")
    
    
    
    
    
    
    
#自定义异常类
class myEception(Exception):
    def __init__(self,msg):
        self.messgae = msg
        
    #这个方法可以不重写
    def __str__(self, *args, **kwargs):
        return Exception.__str__(self, *args, **kwargs)
    

try:
    raise myEception("触发myEception!")

except myEception as e:
    print(e)

 

posted on 2017-11-29 19:02  gaizhongfeng  阅读(118)  评论(0编辑  收藏  举报