Search code examples
pythonexceptionerror-handlingnameerror

Why does the exception statement not executes when NameError occurs?


After defining a function and try/except/else statements in the following way:

def divide(a, b):
    try:
        a / b
    except:
        return False, 'Error occurred'
    else:
        return True, 'Division successful'

The exception is not raised when the argument given to the function is a name of an undefined variable. For instance:

divide(2, J)

instead of executing block of code under except statement, following error is displayed:

NameError: name 'J' is not defined

I have tried rewriting the except statement (except NameError:), but to no avail.

I would be grateful if someone could explain why the except statement is not executed in this case, and how can the execution of it be ensured in case of NameError?


Solution

  • J is a variable in your case, which is not defined. Even before the function runs, J is being called but doesn't exists, hence your error: name 'J' is not defined. I assume you want to test your function with divide(2, "J") which passes the parameter as a string. That should raise the except as desired.