Python:万能异常之`try:` `except <Errortype> as <alias> :` `else:` `finally:`(转)

万能异常之try: except <Errortype> as <alias> : else: finally:(转)

链接: try: except <Errortype> as <alias> : else: finally:

# myExample.py

print('我是外部程序')
try:
    num1 = int(input('给出第一个数字:'))
    num2 = int(input('给出第二个数字:'))
    print(num1 + num2)

except ValueError as v:
    print('ValueError.',v)

except:
    print('Other errors')

else:
    print('No error')

finally:
    print('Error part has been runned')

不同的输入和程序的不同执行

情形1:

# 我是外部程序
# 给出第一个数字:1
# 给出第二个数字:2
# 3
# No error
# Error part has been runned
#

情形2:

# 我是外部程序
# 给出第一个数字:a
# ValueError. invalid literal for int() with base 10: 'a'
# Error part has been runned
# 
posted on 2021-01-23 23:13  摸鱼time  阅读(79)  评论(0编辑  收藏  举报