TypeError:exceptions must be old-style classes or derived from BaseException, not str
Asked Answered
B

3

53

Following is my code:

test = 'abc'
if True:
    raise test + 'def'

And when i run this, it gives me the TypeError

TypeError: exceptions must be old-style classes or derived from BaseException, not str

So what kind of type should the test be?

Bespeak answered 16/7, 2012 at 1:48 Comment(0)
D
64

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).

Try this:

test = 'abc'
if True:
    raise Exception(test + 'def')
Dressingdown answered 17/7, 2012 at 3:25 Comment(0)
B
37

You can't raise a str. Only Exceptions can be raised.

So, you're better off constructing an exception with that string and raising that. For example, you could do:

test = 'abc'
if True:
    raise Exception(test + 'def')

OR

test = 'abc'
if True:
    raise ValueError(test + 'def')

Hope that helps

Brooklynese answered 16/7, 2012 at 1:52 Comment(1)
Also you cannot just raise without any argument.Sway
S
19

It should be an exception.

You want to do something like:

raise RuntimeError(test + 'def')

In Python 2.5 and below, your code would work, as then it was allowed to raise strings as exceptions. This was a very bad decision, and so removed in 2.6.

Sylviesylvite answered 16/7, 2012 at 1:50 Comment(3)
Could you explain why it is so bad to raise a string as an exception?Redware
@Redware Problems with string exceptions include only sometimes working when a literal is used in both the raise and the except, not providing an OO mechanism for attaching additional information to the exception, and not allowing catching categories of multiple exception types. Exceptions were added to the language before classes, and once exception classes were added string exceptions were only kept for backwards compatibility. Their removal, like any (mis-)feature removal, simplified the language.Sylviesylvite
Thanks for mentioning the version where this feature was last supported. That helped me.Glamorize

© 2022 - 2024 — McMap. All rights reserved.