异常处理

0x01 try...except 结构

#coding:utf-8
score = input("输入成绩:")
try:
    score = int(score)
    if(0<=score<=100):
        print("成绩为:",score)
    else:
        print("成绩错误!不在范围内")
except Exception as e:
    print("数值输入错误")

0x02 try...except...else... 结构

没有出现错误就执行else的内容

score = input("输入成绩:")
try:
    score = int(score)
except Exception as e:
    print("输入数值错误")
else:
    if (0 <= score <= 100):
         print("成绩为:",score)
    else:
        print("成绩错误!不在范围内")

0x03 try...except...finally... 结构

无论try子句是否正常的执行,finally子句中的代码块总会得到执行,常常用来做清理工作的

a = int(input("a:"))
b = int(input("b:"))
try:
    c = a/b
    print(c)
except Exception as e:
    print("b can't be 0")
finally:
    print("运行结束!")

原文地址:https://www.cnblogs.com/yicunyiye/p/13944123.html