以下是我的代码:类型错误:例外必须是老式类或BaseException衍生,而不是str的
test = 'abc'
if True:
raise test + 'def'
当我运行它,它给我的TypeError
TypeError: exceptions must be old-style classes or derived from BaseException, not str
所以test
应该是什么样的类型?
以下是我的代码:类型错误:例外必须是老式类或BaseException衍生,而不是str的
test = 'abc'
if True:
raise test + 'def'
当我运行它,它给我的TypeError
TypeError: exceptions must be old-style classes or derived from BaseException, not str
所以test
应该是什么样的类型?
唯一的参数,以提高指示要抛出的异常。这必须是异常实例或异常类(从Exception派生的类)。
试试这个:
test = 'abc'
if True:
raise Exception(test + 'def')
它应该是一个例外。
你想要做的事,如:
raise RuntimeError(test + 'def')
在Python 2.5及以下,你的代码会工作,因为然后使其提高字符串作为例外。这是一个非常糟糕的决定,因此在2.6中删除。
您不能raise
a str
。 d。只有Exception
s可以是raise
d。
所以,你最好用该字符串构造一个异常并提高它。例如,你可以这样做:
test = 'abc'
if True:
raise Exception(test + 'def')
OR
test = 'abc'
if True:
raise ValueError(test + 'def')
希望帮助
你也不能没有任何争论地提出。 – 2015-09-14 09:48:19
你能解释一下为什么它是如此糟糕,提高一个字符串作为例外? – BioGeek 2013-06-05 08:08:27
@BioGeek字符串异常的问题包括:有时只有在'raise'和'except'中使用一个字面值时才会工作,不提供OO机制来将附加信息附加到异常,并且不允许捕获多个异常类型的类别。在类之前的语言中添加了异常,并且一旦添加了异常类,字符串异常仅保留用于向后兼容。与任何(错误)特征删除一样,它们的删除简化了语言。 – 2013-06-05 16:05:15
感谢您提及上次支持此功能的版本。这帮助了我。 – SpaceTrucker 2013-07-29 13:19:50