Search code examples
pythonexceptionnameerror

NameError Handling in Python


I am new to python and I had some difficulty to understand why the {try... except} worked well with below code:

try:
   print(x)
except NameError:
   print('variable x is not defined')

but it did not work with the below code:

def divide(x, y):
    try:
        result = x / y
    except (ZeroDivisionError, NameError):
        print("division by zero!")
    except NameError:
        print('only numeric values')
    else:
        return result
        # print("result is", result)

print(divide(4,f))

Solution

  • There are few problems in your code.

    As is, NameError would be raised by:

    print(divide(4,f))
    

    because there is no f.

    You would have to handle the exception where it's raised, i.e.:

    try:
        print(divide(4,f))
    except NameError:
        print('variable f is not defined')
    

    Now when you look into the function itself, this line:

    except (ZeroDivisionError, NameError):
    

    means the following block gets executed when either ZeroDivisionError or NameError is raised. So the following:

    except NameError:
    

    never gets to play. And the message sort of suggest you were perhaps looking for something like TypeError. E.g. when you wanted a number, but got for instance a str.

    And NameError essentially meaning variable not defined, you would never (OK, unless you del it) see it accessing x or y in a function that accepts these two as arguments. You could see TypeError calling it without an expected positional argument, but in that function x and y will be there.