python基础8.0:程序异常处理

﹥>﹥吖頭↗ 提交于 2020-02-05 13:22:35
解释器触发异常try:    pass    #代码块,逻辑except Exception as e:    #e是Exception对象,对象中封装了错误信息    #上述代码块如果出错,自动执行当前块内容
while True:
    try:
        inp = input('请输入数字:')
        i = int(inp)
    except Exception as e:
        print(e)
        i = 1
    print(i)


try:
    int('e')
except IndexError as e:
    print('indexerror',e)
except ValueError as e:
    print('valueerror',e)
except Exception as e:
    print('不清楚是什么错误:',e)
else:        #没有触发错误执行
    print('??')
finally:     #始终执行
    print('....')

主动触发异常

try:
    #主动出发异常
    raise Exception('主动抛出异常')
except Exception as e:
    print(e)

 

自定义异常

#自定义异常

class oldboyerror(Exception):

    def __init__(self,mag):
        self.massge = mag

    def __str__(self):
        return self.massge

try:
    raise oldboyerror('我错了')
except oldboyerror as e:
    print(e)    #e 对象的__str__()方法,获取返回值

断言

 

assert 条件      强制用户服从,不服从就报错,可捕获,一般不捕获

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!