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

问题描述

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



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

解决方案

这两种类型之间的区别很小。实际上,即使是Python的开发人员,也同意在Python 3中没有任何真正的区别,并删除了 IOError (现在它是一个别名为 OSError )。请参阅:

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



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

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

再次引用PEP:


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:

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:

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

10-20 23:31