Difference between IOError and OSError?

旧巷老猫 提交于 2019-12-03 11:33:34

问题


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.


回答1:


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 and IOError, 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 not IOError, or the reverse.



来源:https://stackoverflow.com/questions/29347790/difference-between-ioerror-and-oserror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!