当“尝试.. IOError除外”时如何处理FileNotFoundError?没有抓住吗? [英] How to handle FileNotFoundError when "try .. except IOError" does not catch it?

查看:136
本文介绍了当“尝试.. IOError除外”时如何处理FileNotFoundError?没有抓住吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python 3上捕获错误?我在Google上搜索了很多,但似乎没有一个答案。文件open.txt不存在,因此应打印e.errno。

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.

这是我现在尝试的内容:

This is what I tried now:

这是在我定义的函数中

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'


推荐答案

FileNotFoundError OSError 的子类,捕获该异常或异常本身:

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

except OSError as e:

操作系统异常已在Python 3.3中进行了修改; IOError 已合并到 OSError 中。请参见 PEP 3151:新功能文档中的OS和IO异常层次结构部分

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

有关详细信息,请参见 OS异常部分,请向下滚动以获取

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

也就是说,您的代码应该仍然可以正常工作,作为 IOError 现在是 OSError 的别名:

That said, your code should still just work as IOError is now an alias for OSError:

>>> IOError
<class 'OSError'>

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

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?

这篇关于当“尝试.. IOError除外”时如何处理FileNotFoundError?没有抓住吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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