首页 > 其他 > 详细

异常处理

时间:2018-10-28 18:48:27      阅读:114      评论:0      收藏:0      [点我收藏+]

异常处理,虽然程序出错了,但是可以做一些预处理,使得程序不崩溃

data = {name:ABCD,
        age:22}
aa = [1,2,3,4]
try:
    data[naaa]
    aa[5]

# except (KeyError,IndexError) as e:
#     print()   #当出现错误后处理方法一样,可以用这种方法
#------分别抓取错误----
# except KeyError as e:
#     print("the key is error",e)
# except IndexError as e:
#     print("the index ",e)
except Exception as e:
    print("出错了",e)    # 能基本抓住所有错误,常用第二种方法

其他方式

data = {name:ABCD,
        age:22}
aa = [1,2,3,4]
try:
    # data[‘naaa‘]
    aa[2]

except KeyError as e:
    print("the key is error",e)
except IndexError as e:
    print("the index ",e)
except Exception as e:
    print("未知错误",e)
else:
    print("else,如果没有错,执行")
finally:
    print("finally不管有没有错,都执行")

# else,如果没有错,执行
# finally不管有没有错,都执行

自己写的异常

class ABCException(Exception):
    def __init__(self,msg):
        self.msg = msg

    def __str__(self):   # __str__ 可以自定义,也可以不写使用基类的
        return self.msg

try:
    raise ABCException("自己写的异常")    #自己写的异常需要自己触发
except ABCException as e:
    print(e)

 

异常处理

原文:https://www.cnblogs.com/yfjly/p/9866229.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!