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

如何让try-except语句多次捕获错误?计算器菜单输入异常问题

问题:计算器菜单输入的异常捕获仅生效一次,递归调用引发UnboundLocalError

正在开发带菜单的计算器应用,输入无效内容(如字符串)时会抛出ValueError,用try-except捕获但仅能生效一次;再次输入无效内容时异常无法被捕获。尝试在except块中递归调用get_user_choice(),却触发了UnboundLocalError异常。

原代码

def get_user_choice():
    try:
        user_choice = int(input("Choice: "))
    except ValueError:
        print("\nERROR: Please enter a valid integer value. Retrying...\n")
        time.sleep(0.5)
        show_menu()
        user_choice = int(input("Choice: "))
        pass

修改后代码

def get_user_choice():
    try:
        user_choice = int(input("Choice: "))
    except (ValueError, UnboundLocalError):
        print("\nERROR: Please enter a valid integer value. Retrying...\n")
        time.sleep(0.5)
        show_menu()
        get_user_choice()
        pass

问题分析

  1. 原代码缺陷:except块中仅重新执行了一次int(input())转换,若这次仍输入无效值,没有额外的异常捕获逻辑,导致第二次无效输入直接抛出未被处理的ValueError。
  2. 修改后代码缺陷:递归调用get_user_choice()后,未将递归返回的结果赋值给user_choice变量,函数执行结束时该变量未被定义,因此触发UnboundLocalError。

正确解决方案

用循环持续获取输入,直到得到有效的整数,逻辑更清晰且避免变量未定义问题:

import time

def show_menu():
    # 示例菜单展示逻辑
    print("\n=== 计算器菜单 ===")
    print("1. 加法运算")
    print("2. 减法运算")
    print("3. 退出程序")

def get_user_choice():
    while True:
        try:
            user_choice = int(input("\nChoice: "))
            return user_choice  # 输入有效,返回结果并退出循环
        except ValueError:
            print("\nERROR: 请输入有效的整数!重试中...")
            time.sleep(0.5)
            show_menu()

方案说明

  • while True构建无限循环,直到用户输入有效整数后通过return退出循环。
  • 每次捕获ValueError后,提示错误、短暂等待、重新显示菜单,然后回到循环开头重新获取输入,无论用户输入多少次无效内容,都会被持续捕获处理。
  • 不存在变量未定义问题,因为只有输入有效时才会返回user_choice,无效输入会一直留在循环内重试。

内容的提问来源于stack exchange,提问作者Dillon Teakell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:01:24