NameErrorEasy Examples

Raised when a variable name is not found in scope

Triggering NameError

How NameError is raised and how to catch it.

python
# Triggering and catching NameError
try:
    print(undefined_variable)
except NameError as e:
    print(f"Caught NameError: {e}")
    print(f"Type: {type(e).__name__}")

NameError is raised when raised when a variable name is not found in scope. Always catch specific exceptions rather than bare except clauses.

Handling NameError

Basic error handling pattern for NameError.

python
# Safe handling pattern
def safe_operation():
    try:
        print(undefined_variable)
    except NameError:
        print("Operation failed gracefully")
        return None

result = safe_operation()
print(f"Result: {result}")

Wrapping risky operations in try/except blocks prevents your program from crashing.

Want to try these examples interactively?

Open Easy Playground