OSError

OSError is a built-in exception that acts as the base class for system-related errors in Python, that include file handling, hardware issues, or other low-level OS tasks.

It’s a base class for many more specific errors related to interactions with your operating system, such as FileNotFoundError, PermissionError, or ConnectionError and its subclasses.

You might encounter OSError when you programmatically interact with your operating system, doing file manipulation, network communication, or process management.

OSError Occurs When

  • Python hits an OS-level error code that doesn’t match a more specific subclass
  • You explicitly raise OSError in your code
  • A platform or environment doesn’t implement a matching specialized exception

OSError Can Be Used When

You can catch OSError to handle any system-level problems, including all its subclasses. For instance, catching OSError will also catch FileNotFoundError, PermissionError, or any other subclass that Python raises.

Example

An example that triggers a raw OSError for a bad file descriptor:

Python
>>> import os
>>> file_descriptor = os.open("example.txt", os.O_CREAT)
>>> os.close(file_descriptor)
>>> # Attempt to read from a closed descriptor
>>> os.read(file_descriptor, 100)
...
Traceback (most recent call last):
    ...
OSError: [Errno 9] Bad file descriptor

An example of how you can handle OSError with a tryexcept block:

Python
>>> import os
>>> try:
...     file_descriptor = os.open("example.txt", os.O_CREAT)
...     os.close(file_descriptor)
...     os.read(file_descriptor, 100)
... except OSError as e:
...     print(f"Error occurred: {e}")
...
Error occurred: [Errno 9] Bad file descriptor

Note that you’ll also catch the subclasses of OSError when you write except OSError. Usually, it’s better to be more specific and catch the subclass exception directly.

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 20, 2025 • Reviewed by Martin Breuss