为什么仅仅使用 if 不够:深入理解 Python 中的 try/except

发布: (2025年12月20日 GMT+8 19:29)
2 min read
原文: Dev.to

Source: Dev.to

关于 “Why if Is Not Enough: Understanding try/except in Python” 的封面图片

为什么仅靠 if 不够

当我在 Python 中编写小费计算器(完整代码可查看我的 GitHub)时,我发现即使使用了 if 条件,错误仍然会发生。

原因在于 if 条件是在类型转换 之后 执行的,而错误发生在 转换本身 的过程中。

def get_bill_amount(prompt: str) -> float:
    while True:
        value = input(prompt).strip()
        try:
            amount = float(value)
            if amount > 0:
                return amount
            print("Amount must be greater than 0.")
        except ValueError:
            print("Please enter a valid number.")
  • 期望的用户输入: 大于 0 的数字
  • 类型不匹配: 当用户输入类似 abc 的字符串时
  • 错误: 程序因 ValueError: could not convert string to float 而崩溃

关键在于 float(value) 是一个风险操作。如果转换失败,Python 会在检查 if 条件之前抛出错误。

使用 value.isdigit() 看似安全,但它会对合法输入如 12.5-3,甚至带空格的 10 失效。这正是 try/except 存在的原因。

经验法则

  • if → 检查逻辑(规则、范围、条件)
  • try/except → 捕获崩溃(如类型转换等无效操作)

始终使用 if 来验证规则,使用 try/except 来防止程序崩溃。

Back to Blog

相关文章

阅读更多 »