ModuleNotFoundErrorEasy Examples

Subclass of ImportError; raised when a module cannot be located

Triggering ModuleNotFoundError

How ModuleNotFoundError is raised and how to catch it.

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

ModuleNotFoundError is raised when subclass of importerror; raised when a module cannot be located. Always catch specific exceptions rather than bare except clauses.

Handling ModuleNotFoundError

Basic error handling pattern for ModuleNotFoundError.

python
# Safe handling pattern
def safe_operation():
    try:
        import nonexistent_module_xyz
    except ModuleNotFoundError:
        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