24 python初学(异常)

try, except, else, finally
执行顺序:1. 先执行 try 里面的代码块,如果发生异常就会去捕获。
2. 没有错误就会执行 else 里面的信息。
3. 无论怎样都会执行 finally 里面的信息

raise Exception('不过了。。'): 主动抛出一个异常

try:
    #代码块,逻辑
    i = int(input('input'))
except Exception as e:
    # e是Exception的对象,对象中封装了错误信息
    # 上述代码块如果出错,自动执行当前块的内容
    print(e)
    i = 1
print(i)
try:
    li = [11, 22]
    # 主动触发异常
    raise Exception('不过了。。')
    li[999]
    li['lk']
# 只捕获某种特定的异常,是Exception的子类
except IndexError as e:
    print(e)
except ValueError as e:
    print(e)
except Exception as e:
    print('Exception: %s' % e)
# 不出错执行else里面的代码
else:
    print('else')
# 出不出错都会执行finally里面的代码
finally:
    print('finally')
猪猪侠要努力呀!
原文地址:https://www.cnblogs.com/mlllily/p/10317677.html