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

PythonTypeerrorRaise

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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')

Solution 2 - Python

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

Solution 3 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question2342G456DI8View Question on Stackoverflow
Solution 1 - Pythonuser1393258View Answer on Stackoverflow
Solution 2 - PythoninspectorG4dgetView Answer on Stackoverflow
Solution 3 - PythonAbe KarplusView Answer on Stackoverflow