OSError
OSError is a built-in exception that acts as the base class for system-related errors in Python, including 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 interacting with your operating system programmatically, performing 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
OSErrorin your code - A platform or environment doesn’t implement a matching specialized exception
OSError Can Be Used When
You need to handle system-level problems, including all of OSError’s subclasses. For example, catching OSError will also catch FileNotFoundError, PermissionError, and any other related subclass that Python raises.
OSError Examples
Here’s 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
This is 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)
- Working With Python's Built-in Exceptions (Course)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Raising and Handling Python Exceptions (Course)
- Introduction to Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)