How to catch NameError Exception in Python?

PythonServer Side ProgrammingProgramming

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


raja
Published on 06-Dec-2017 13:09:26
Advertisements