NotADirectoryErrorEasy Examples

Raised when a directory operation is attempted on a non-directory

Triggering NotADirectoryError

How NotADirectoryError is raised and how to catch it.

python
# Triggering and catching NotADirectoryError
try:
    raise NotADirectoryError("not a directory")
except NotADirectoryError as e:
    print(f"Caught NotADirectoryError: {e}")
    print(f"Type: {type(e).__name__}")

NotADirectoryError is raised when raised when a directory operation is attempted on a non-directory. Always catch specific exceptions rather than bare except clauses.

Handling NotADirectoryError

Basic error handling pattern for NotADirectoryError.

python
# Safe handling pattern
def safe_operation():
    try:
        raise NotADirectoryError("not a directory")
    except NotADirectoryError:
        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