Python 当“try .. except IOError”未捕获时如何处理 FileNotFoundError?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28633555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:32:33  来源:igfitidea点击:

How to handle FileNotFoundError when "try .. except IOError" does not catch it?

pythonexceptionpython-3.xtry-catch

提问by Thomas W

How can I catch an error on python 3? I've googled a lot but none of the answers seem to be working. The file open.txt doesn't exist so it should print e.errno.

如何在 python 3 上捕获错误?我用谷歌搜索了很多,但似乎没有一个答案有效。文件 open.txt 不存在,所以它应该打印 e.errno。

This is what I tried now:

这是我现在尝试的:

This is in my defined function

这是在我定义的函数中

try:
    with open(file, 'r') as file:
        file = file.read()
        return file.encode('UTF-8')
except OSError as e:
    print(e.errno)

However I does not print anything when I get this error

但是,当我收到此错误时,我没有打印任何内容

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

采纳答案by Martijn Pieters

FileNotFoundErroris a subclass of OSError, catch that or the exception itself:

FileNotFoundErrorOSError、 catch 或异常本身的子类:

except OSError as e:

Operating System exceptions have been reworked in Python 3.3; IOErrorhas been merged into OSError. See the PEP 3151: Reworking the OS and IO exception hierarchysectionin the What's New documentation.

操作系统异常已在 Python 3.3 中重新设计;IOError已合并到OSError. 请参阅新功能文档中的PEP 3151:重新处理 OS 和 IO 异常层次结构部分

For more details the OS Exceptionssectionfor more information, scroll down for a class hierarchy.

有关更多详细信息,请向下滚动以查看类层次结构的OS Exceptions部分

That said, your code should still just workas IOErroris now an alias for OSError:

也就是说,您的代码仍然应该IOError现在的别名一样工作OSError

>>> IOError
<class 'OSError'>

Make sure you are placing your exception handler in the correct location. Take a close look at the traceback for the exception to make sure you didn't miss where it is actually being raised. Last but not least, you did restart your Python script, right?

确保将异常处理程序放置在正确的位置。仔细查看异常的回溯,以确保您没有错过实际引发异常的位置。最后但并非最不重要的一点是,您确实重新启动了 Python 脚本,对吗?