Catch NameError Exception in Python



Whenever Python comes across a variable or name that is not defined in the local or global namespace, it raises a NameError. This helps in debugging and ensures that variables are properly declared before using it.

There are various ways to catch and handle a NameError in Python. The most common method is using a try-except block. Below are different approaches to catch a NameError exception -

  • Using try-except block with NameError
  • Using try-except-else block
  • Using try-except-finally block

Using try-except Block with NameError

In Python, you can catch a NameError by writing the code inside a try block and handling the error using an except block. This prevents the program from crashing if the variable is not defined.

Example

In the following example, we try to print a variable that has not been defined. The NameError is caught using an except block -

try:
   print(x) 
except NameError: 
   print("Variable x is not defined") 

The output of the above program is displayed as follows -

Variable x is not defined

Using try-except-else Block

We can use the try-except-else block when we want to separate the error-handling code from the normal code. If no error occurs in the try block, the code inside the else block runs.

Example

In this example, the try block will raise a NameError, so the else block will be skipped -

try:
   print(y)
except NameError:
   print("Variable y is not defined")
else:
   print("No NameError occurred")

The output of the above program is displayed as follows -

Variable y is not defined

Using try-except-finally Block

The try-except-finally block ensures that the code inside the finally block is always executed, irrespective of whether an error occurred or not. It is useful for cleaning up resources or printing final messages.

Example

In this example, even though a NameError occurs, the message in the finally block is still printed -

try:
   print(z)
except NameError:
   print("Variable z is not defined")
finally:
   print("Execution completed")
Variable z is not defined
Execution completed

User-defined Variable Before Declaration

If we try to use a user-defined function or variable before defining it, Python generates a NameError. By handling this error, we are stopping the program from terminating abruptly.

Example

In the following example, we are calling a function that is not defined -

try:
   greet()
except NameError:
   print("Function greet() is not defined")

Following is an example of the above program -

Function greet() is not defined
Updated on: 2025-05-26T13:34:55+05:30

612 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements