TypeError:exception必须是旧式类或派生自BaseException,而不是str

234*_*DI8 43 python raise typeerror

以下是我的代码:

test = 'abc'
if True:
    raise test + 'def'
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它给了我 TypeError

TypeError: exceptions must be old-style classes or derived from BaseException, not str
Run Code Online (Sandbox Code Playgroud)

那应该test是什么类型的?

小智 57

提出的唯一论据表明要提出的例外.这必须是异常实例或异常类(派生自Exception的类).

试试这个:

test = 'abc'
if True:
    raise Exception(test + 'def')
Run Code Online (Sandbox Code Playgroud)


ins*_*get 35

你不能raise一个str.只有Exceptions可以是raised.

所以,你最好用该字符串构造一个异常并提高它.例如,您可以这样做:

test = 'abc'
if True:
    raise Exception(test + 'def')
Run Code Online (Sandbox Code Playgroud)

要么

test = 'abc'
if True:
    raise ValueError(test + 'def')
Run Code Online (Sandbox Code Playgroud)

希望有所帮助


Abe*_*lus 16

这应该是一个例外.

你想做的事情如下:

raise RuntimeError(test + 'def')
Run Code Online (Sandbox Code Playgroud)

在Python 2.5及更低版本中,您的代码可以正常工作,因为它允许将字符串作为异常引发.这是一个非常糟糕的决定,因此在2.6中删除了.

  • @BioGeek字符串异常的问题仅包括在`raise`和`except`中使用文字时有时工作,不提供用于将附加信息附加到异常的OO机制,并且不允许捕获多个异常类型的类别.在类之前将异常添加到语言中,并且一旦添加了异常类,则仅保留字符串异常以用于向后兼容性.与任何(错误)功能删除一样,它们的删除简化了语言. (3认同)
  • 你能解释一下为什么将字符串作为异常提升是如此糟糕吗? (2认同)