Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch NameError Exception in Python?

If I run the following code, I get an error

def foo():
    print magnolia
foo ()

How to catch this exception and find its type?


1 Answer
codefoxx

NameErrors are raised when your code refers to a name that does not exist in the current scope. For example, an unqualified variable name.

The given code is rewritten as follows to catch the exception and find its type.

import sys
try:
def foo():
print magnolia
foo()
except NameError as e:
print e
print sys.exc_type

OUTPUT

C:/Users/TutorialsPoint1/~.py
global name 'magnolia' is not defined
<type 'exceptions.NameError'>

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.