fender4645 fender4645 - 7 months ago 33
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>
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:

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

Does that make sense?


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'