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中删除了.