try:A
except errorpypeB:C
执行命令字段A,没有出现错误正常运行;如果出现错误,且错误类型是B,就运行C;反之,出现错误但不是C,报错。
如果不加B,无论出现什么错误都运行C。
try:
score=input('请输入考试成绩')
if score>=90:
print('A')
elif 80<=score<90:
print('b')
elif 70<=score<80:
print('c')
else:
print('d')
except:
print('输入的成绩是非数值型的')
运行结果:
请输入考试成绩44
输入的成绩是非数值型的
Process finished with exit code 0
try:
score=input('请输入考试成绩')
if score>=90:
print('A')
elif 80<=score<90:
print('b')
elif 70<=score<80:
print('c')
else:
print('d')
except NameError:
print('输入的成绩是非数值型的')
运行结果:
请输入考试成绩44
Traceback (most recent call last):
File "D:\璐\软件\python\pythonProject\tipdm2.py", line 11, in <module>
if score>=90:
TypeError: '>=' not supported between instances of 'str' and 'int'
Process finished with exit code 1
try:
score=input('请输入考试成绩')
if score>=90:
print('A')
elif 80<=score<90:
print('b')
elif 70<=score<80:
print('c')
else:
print('d')
except TypeError:
print('输入的成绩是非数值型的')
运行结果:
请输入考试成绩44
输入的成绩是非数值型的
Process finished with exit code 0
try:
score=input('请输入考试成绩')
if score>=90:
print('A')
elif 80<=score<90:
print('b')
elif 70<=score<80:
print('c')
else:
print('d')
except BaseException:
print('输入的成绩是非数值型的')
运行结果:
请输入考试成绩44
输入的成绩是非数值型的
Process finished with exit code 0
附:
Python中部分异常: