【问题标题】:Python: Why doesn't this throw an exception?Python:为什么这不抛出异常?
【发布时间】:2025-03-06 17:15:02
【问题描述】:

以下代码返回:

TypeError: cannot concatenate 'str' and 'int' objects

为什么不抛出异常?

while True:
    try:
        print "test" + 1
    except ValueError:
        print "You can't concatenate that different object types silly"

【问题讨论】:

  • ValueErrorTypeError 不是同一个词
  • 它没有运行对你有好处,如果你用TypeError替换ValueError那是一个无限循环!
  • catch ValueError: 更改为catch TypeError:。并删除while True,显然,除非你想看到你的错误信息无限重复。
  • 谢谢!我是新手,没有意识到这些异常类型意味着什么。
  • @Kevin 嗯,Python 使用 except,而不是 catch。 ;)

标签: python python-2.7 error-handling try-catch


【解决方案1】:

你可以像这样捕获异常:

try:
    print "test" + 1
except ValueError:
    print "You can't concatenate that different object types silly"
except TypeError:
    print "TypeError and the words you want to say"

【讨论】: