Computer >> Computer tutorials >  >> Programming >> Python

How to catch NameError Exception in Python?


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.

Example

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'>