Operating system-related error
Raised when a system function returns a system-related error, including I/O failures like 'file not found' or 'disk full'. It's a base class for many more specific exceptions like `FileNotFoundError` and `PermissionError`.
- 1An underlying issue with the operating system, such as running out of file descriptors.
- 2Interacting with the filesystem in an invalid way, like trying to create a directory that already exists.
- 3Hardware errors, such as a disk failure or a network interface going down.
This is a general error. A specific example is trying to create a directory that already exists, which raises a `FileExistsError`, a subclass of `OSError`.
import os
os.mkdir("existing_directory") # Assuming this directory already exists
expected output
Traceback (most recent call last): File "<stdin>", line 2, in <module> FileExistsError: [Errno 17] File exists: 'existing_directory'
Fix 1
Catch specific subclasses instead of base `OSError`
WHEN You want to handle different OS-level errors in different ways.
import os
try:
os.mkdir("my_dir")
except FileExistsError:
print("Directory 'my_dir' already exists.")
except PermissionError:
print("Do not have permission to create 'my_dir'.")
Why this works
Catching more specific exceptions allows for more granular and appropriate error handling logic, rather than treating all OS errors the same.
Fix 2
Check for conditions before acting
WHEN You can prevent the error from happening in the first place.
import os
dir_path = "my_dir"
if not os.path.exists(dir_path):
os.mkdir(dir_path)
Why this works
This 'Look Before You Leap' (LBYL) approach avoids the error by first checking if the condition that would cause it is true.
import os
os.mkdir("existing_dir") # FileExistsError (subclass of OSError)try:
os.mkdir("my_dir")
except FileExistsError:
pass # already exists
except PermissionError as e:
print(f"Permission denied: {e}")import os
os.makedirs("my_dir", exist_ok=True) # never raises FileExistsError✕ Catching the base `OSError` and ignoring it
`OSError` can signify serious problems (like a full disk or hardware failure) that should almost never be ignored silently.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev