python基础——异常处理

当有些时候我们会试图使用某些方法,来达到自己想要的目的,但有时却可能缺少我们想要的对象而报错,这时候就需要用到异常处理。

简单的异常处理:

try:
    print(list[14])
except IndexError as e:
    print('捕获了一个索引错误{}'.format(e))

当我们可能会出现未知错误时可以使用Exception来捕获错误:

try :
    print(list[21])
# Exception 和 IndexError , KeyError ...
# 为父与子的关系
except Exception as e:
    print('捕获了一个错误{}'.format(e))

标准的格式:

try:
    print('这是一个标准格式')
    print(dic['data'])
except IndexError as e:
    print('上一行代码出现了索引错误{}'.format(e))
except KeyError as e:
    print('上一行代码出现了关键字错误{}'.format(e))
# 如果没有出现任何错误 即执行代码块
else:
    print('目前代码感觉良好')
finally:#无论有没有报错都执行
    print('代码结束')

可以用raise + Exception 抛出异常:

age = input('请输入你的年龄')
age = int(age)
if age < 0:
    print('年龄不对')
    # raise 升起;在此只抛出错误
    # 手动抛出异常
    raise Exception('年龄不对,请务必输入一个大于0的数值')

猜你喜欢

转载自blog.csdn.net/za_pai_xiao_ba/article/details/80917760