IOError和OSError之间的区别? [英] Difference between IOError and OSError?

查看:2305
本文介绍了IOError和OSError之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是对一个函数是否会引发IOError或OSError(或两者都)感到困惑?这些异常类型背后的原则规则是什么?它们之间有什么区别?什么时候提出这些异常?



我最初以为OSError是为了拒绝许可,但是没有权限打开一个文件会引发一个IOError。

解决方案

这两种类型之间的区别很小。实际上,即使是Python的开发人员,也同意在Python 3中没有任何真正的区别,并删除了 IOError (现在它是一个别名为 OSError )。请参阅 PEP 3151 - 重新操作操作系统和IO异常层次结构


虽然这些区别中的一些可以通过实现注意事项来解释,但它们在更高层次。例如,分隔 OSError IOError 的行往往模糊。请考虑以下内容:

 >>> os.remove(fff)
追溯(最近的最后一次调用):
文件< stdin>,第1行,< module>
OSError:[Errno 2]没有这样的文件或目录:'fff'
>>> open(fff)
追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
IOError:[Errno 2]没有这样的文件或目录:'fff'


是的,这是两个不同的异常类型,具有完全相同的错误消息。



对于您自己的代码,坚持投掷 OSERROR 。对于现有的功能,请检查文档(它应该详细说明您需要捕获的内容),但您可以安全地捕获两者:

  try :
#...
except(IOError,OSError):
#handle error

再次引用PEP:


其实,很难想到任何情况,其中而不是 IOError ,反之亦然。



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.

解决方案

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.

这篇关于IOError和OSError之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆