Python try except 块不会引发正确的错误

问题描述 投票:0回答:1

我有以下代码:

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 错误。为什么? (我一直在网上搜索但找不到例子)

python-3.x try-catch
1个回答
0
投票

因为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
© www.soinside.com 2019 - 2024. All rights reserved.