【发布时间】:2012-07-14 21:11:41
【问题描述】:
以下是我的代码:
test = 'abc'
if True:
raise test + 'def'
当我运行它时,它给了我TypeError
TypeError: exceptions must be old-style classes or derived from BaseException, not str
那么test应该是什么类型呢?
【问题讨论】:
以下是我的代码:
test = 'abc'
if True:
raise test + 'def'
当我运行它时,它给了我TypeError
TypeError: exceptions must be old-style classes or derived from BaseException, not str
那么test应该是什么类型呢?
【问题讨论】:
应该是个例外。
你想做这样的事情:
raise RuntimeError(test + 'def')
在 Python 2.5 及更低版本中,您的代码可以工作,因为它允许引发字符串作为异常。这是一个非常糟糕的决定,因此在 2.6 中被删除。
【讨论】:
raise 和 except 中都使用文字时才起作用,不提供用于将附加信息附加到异常的 OO 机制,而不是允许捕获多种异常类型的类别。异常是在类之前添加到语言中的,一旦添加了异常类,字符串异常只保留用于向后兼容。它们的删除,就像任何(错误)功能删除一样,简化了语言。
你不能 raise 和 str。只有Exceptions 可以是raised。
所以,你最好用那个字符串构造一个异常并引发它。例如,您可以这样做:
test = 'abc'
if True:
raise Exception(test + 'def')
或
test = 'abc'
if True:
raise ValueError(test + 'def')
希望有帮助
【讨论】:
raise 的唯一参数表示要引发的异常。这必须是异常实例或异常类(派生自 Exception 的类)。
试试这个:
test = 'abc'
if True:
raise Exception(test + 'def')
【讨论】: