简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM