Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise a string variable as an exception

I'm using a library that will return something like the following when calling one of their functions

result = getResult(foo)
print(result)

The result is a dict

{'errorMessage': "name 'foo' is not defined", 'errorType': 'NameError'}

I want to raise a NameError exception, but the following doesn't work

raise result['errorType'](result['errorMessage'])

It gives a new error

TypeError: 'str' object is not callable

How can I raise an exception who's type is defined from a string variable?

like image 381
Steve Robbins Avatar asked Sep 15 '25 22:09

Steve Robbins


2 Answers

The value of result["errorType"] is a string that names an error class, not the error class itself.

If the error type will always be a built-in type, you can look it up in __builtins__.

raise getattr(__builtins__, result['errorType'])(result['errorMessage'])
like image 142
Barmar Avatar answered Sep 19 '25 16:09

Barmar


You could use eval but carefully:

>>> raise eval(f"{result['errorType']}(\"{result['errorMessage']}\")")

NameError: name 'foo' is not defined
like image 24
not_speshal Avatar answered Sep 19 '25 15:09

not_speshal