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:
>>> 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 try
…except
block:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python Exceptions: An Introduction (Tutorial)
- Reading and Writing Files in Python (Guide) (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)