为什么捕获的list index out of range异常与字符串比对返回False
问题原因
你捕获到的e是IndexError异常类的实例,并非字符串类型。执行print(e)时会自动调用异常对象的__str__方法输出其携带的错误描述文本,所以你能看到list index out of range的输出,但异常对象本身和对应字符串属于完全不同的类型,因此相等判断结果为False。
推荐解决方案
更规范的实现方式是直接捕获指定的IndexError异常,不需要捕获通用Exception后判断错误文本,既精准也不会误匹配其他类型的异常:
if command_keyword == "send": try: globals()[commands[2]].send_funds(globals()[commands[3]], int(commands[1])) except IndexError: print("'send' command requires three arguments. 'send [amount] [sender] [recipient]'")
原理验证方案(不推荐生产使用)
如果要沿用原逻辑验证错误信息,需要先将异常对象转为字符串再做比较:
if command_keyword == "send": try: globals()[commands[2]].send_funds(globals()[commands[3]], int(commands[1])) except Exception as e: if str(e) == 'list index out of range': print("'send' command requires three arguments. 'send [amount] [sender] [recipient]'")
补充提示:直接使用用户输入的内容作为
globals()的键取值调用方法存在代码注入风险,仅适合练习场景使用,正式环境请先对输入做严格的合法性校验。
内容的提问来源于stack exchange,提问作者Elipsus
相关产品推荐
相关产品推荐

