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')

 

相关文章:

  • 2021-05-06
  • 2021-11-20
  • 2021-08-15
  • 2021-10-28
  • 2021-11-25
  • 2021-08-20
  • 2022-12-23
  • 2022-02-10
猜你喜欢
  • 2022-12-23
  • 2022-01-08
  • 2021-12-17
  • 2021-09-29
  • 2021-08-01
  • 2021-07-07
  • 2021-08-03
相关资源
相似解决方案