I am always getting confused on whether a function would raise an IOError or OSError (or both?). What is the principle rule behind these exception types, what is the difference between them and when is which raised?
I've initially thought OSError is for things like permission denial, but opening a file without permissions will raise an IOError.
OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”. Below is an example of OSError: Python.
IOError in Python is a result of incorrect file name or location. This error is raised in multiple conditions and all these conditions can be handled using try except code block. We saw the working of the error with examples and saw how to avoid it. Implementing try except block will save a lot of hard work.
Handling IOErrors in Python During File Operations Let's create a function to reference a file and then we'll handle the IOError. Now, we will delete the file and then try to open it and this will raise the required error. FileNotFoundError is a subclass of IOError.
There is very little difference between the two types. In fact, even the core Python developers agreed that there is no real difference and removed IOError
in Python 3 (it is now an alias for OSError
). See PEP 3151 - Reworking the OS and IO exception hierarchy:
While some of these distinctions can be explained by implementation considerations, they are often not very logical at a higher level. The line separating
OSError
andIOError
, for example, is often blurry. Consider the following:>>> os.remove("fff") Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 2] No such file or directory: 'fff' >>> open("fff") Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'fff'
Yes, that's two different exception types with the exact same error message.
For your own code, stick to throwing OSError
. For existing functions, check the documentation (it should detail what you need to catch), but you can safely catch both:
try: # ... except (IOError, OSError): # handle error
Quoting the PEP again:
In fact, it is hard to think of any situation where
OSError
should be caught but notIOError
, or the reverse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With