我有以下代码:
num2hgh = Exception
txt = 'enter your grade '
while True:
try:
grade = int(input(txt))
print(grade)
if grade > 100:
raise num2hgh
except num2hgh:
txt = 'Grade to high, enter again: '
except ValueError:
txt = 'Please enter an integer; '
else:
break
当我输入 abc 时,我没有收到 ValueError 错误,但一直收到 num2hgh 错误。为什么? (我一直在网上搜索但找不到例子)
因为num2hgh中的Exeption中已经存在ValueError,根据操作顺序,由于Exeption中存在ValueError,所以从那里退出。
如果你像这样修复代码,它就会起作用
num2hgh = Exception
txt = 'enter your grade '
while True:
try:
grade = int(input(txt))
print(grade)
if grade > 2:
raise num2hgh
except ValueError:
txt = 'Please enter an integer; '
except num2hgh:
txt = 'Grade to high, enter again: '
else:
break