fender4645 fender4645 - 1 month ago 7
Python Question

Proper way to handle exception when function returns None

What's the best way to handle a case where a function returns None. For example:

def my_function():
if <some_stuff_works>:
return <stuff>
else:
return None

my_var = my_function()


What I'd like to do is raise an exception if my_var is None and then set to a certain value. So something like:

try:
my_var = my_function()
except ValueIsEmpty:
my_var = "EMPTY"


Does that make sense?

Answer

If you can't modify the function, there's no need to come up with a creative exception: just check if it is None and give it an appropriate value.

my_var = my_function()
if my_var is None:
    my_var = 'default_value'