You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的except块中打印assert抛出的错误信息?

问题根因
  • assert 断言失败时抛出的异常类型为 AssertionError,原有代码的except块仅捕获ValueError,断言触发的异常不会进入该分支,自然无法输出预设的错误提示。
  • 原有代码的except声明未绑定异常实例,即便捕获到对应异常,也无法提取assert语句中附带的自定义错误信息。
  • 存在语法疏漏:except ValueError行末尾缺少冒号,代码无法直接运行。
  • 额外笔误:第一个assert的判断逻辑是a >=200,但配套提示文本写的是must be <= 200,逻辑矛盾。
修正方案
  1. 补充对AssertionError类型的捕获,可根据需求选择和ValueError合并捕获,或拆分不同except分支分别处理两类错误。
  2. 在except语句后通过as 变量名的形式绑定异常实例,直接打印该实例即可获取assert中预设的错误提示。
  3. 补全缺失的语法冒号,修正提示文本的笔误。

修正后可直接运行的代码

try:
    a = int(input('Please enter the first number it must be >= 200' + '\n' + '(note the sum of both numbers must be <=300)'))
    b = int(input('please your second number it must be <= 50'))
    c = a + b
    assert a >= 200 and isinstance(a, int), 'invalid entry for a must be >= 200 and a number'
    assert b <= 50 and isinstance(b, int), 'invalid entry for b must be <=50 and a number'
    assert c <= 300, 'The sum of your numbers is >300'
except (ValueError, AssertionError) as e:
    print(f'error: {e}')
else:
    print('All in range')

分场景处理错误的写法

如果需要区分「输入不是整数」和「数值不符合校验规则」两类错误,可以拆分except块:

try:
    a = int(input('Please enter the first number it must be >= 200' + '\n' + '(note the sum of both numbers must be <=300)'))
    b = int(input('please your second number it must be <= 50'))
    c = a + b
    assert a >= 200 and isinstance(a, int), 'invalid entry for a must be >= 200 and a number'
    assert b <= 50 and isinstance(b, int), 'invalid entry for b must be <=50 and a number'
    assert c <= 300, 'The sum of your numbers is >300'
except ValueError:
    print('error: 请输入合法的整数')
except AssertionError as e:
    print(f'error: {e}')
else:
    print('All in range')

补充说明:由于a和b是通过int()转换赋值的,只要走到assert语句,二者必然是整数类型,isinstance(a, int)、isinstance(b, int)的判断属于冗余逻辑,可以删除简化代码。

内容的提问来源于stack exchange,提问作者Z. Young

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 23:42:09