python's thirty day for me 异常处理

---恢复内容开始---

程序的异常:报错之后程序终止。

  异常处理搭配使用:

l = ['创建老师','创建学校']
while True:
    try:
        for num,item in enumerate(l,1):
            print(num,item)
        index = int(input('num:'))
        print(l[index - 1])
        break
    except ValueError:
        print('请输入一个数字:')
    except IndexError:
        print('请输入选择范围内的数字:')
    except Exception as e:
        print(e)

finally 语句 :必须要和try 搭配使用:

  finally 执行 try 中的代码,不管是否触发了错误,都会执行finally中的代码。

try:
    name
except NameError:
    print('name error')
else:
    print('sucess')
finally:
    print('finally')

try except:try中的代码遇到异常,就执行except中的代码。

try except else:try中的代码遇到异常,就执行except中的代码,没遇到异常就执行else中的代码。

try except else finally:try中的代码遇到异常,就执行except中的代码,没遇到异常就执行else中的代码,无                                论如何都执行finally中的代码。

try finally:不能处理异常了,但是无论是否发生异常,都会执行finally中的代码。

主动触发异常:raise

---恢复内容结束---

原文地址:https://www.cnblogs.com/stfei/p/8965768.html